Uploaded image for project: 'SonarCFamily'
  1. SonarCFamily
  2. CPP-3403

Proposed rule: detect static initialization-order fiasco

    XMLWordPrintable

    Details

      Description

      See: https://en.cppreference.com/w/cpp/language/siof

      Example

      a.cpp:

      #include "header.h"
      int stringLength = str.size();
      

      b.cpp:

      #include "header.h"
      #include <string>
      std::string str{"Buggy"};
      

      header.h:

      #include <string>
      extern int stringLength;
      extern std::string str;
      

      main.cpp:

      #include <iostream>
      #include "header.h"
      
      int main() {
        std::cout <<str <<" has length " <<stringLength <<"\n";
        return 0;
      }
      

      Depending on the compilation order we get different results:

      $ g++ b.cpp a.cpp main.cpp && ./a.out
      > Buggy has length 5
      
      $ g++ a.cpp b.cpp main.cpp && ./a.out
      > Buggy has length 0
      

      In other cases this mighe cause a crash, depending on the order the files are linked in, and the mood of the toolchain.

        Attachments

          Activity

            People

            Assignee:
            Unassigned Unassigned
            Reporter:
            arseniy.zaostrovnykh Arseniy Zaostrovnykh
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Dates

              Created:
              Updated: