Search code examples
c++structinitializationvalgrindcalloc

Proper way to initialize C++ structs


Our code involves a POD (Plain Old Datastructure) struct (it is a basic c++ struct that has other structs and POD variables in it that needs to get initialized in the beginning.)

Based one what I've read, it seems that:

myStruct = (MyStruct*)calloc(1, sizeof(MyStruct));

should initialize all the values to zero, as does:

myStruct = new MyStruct();

However, when the struct is initialized in the second way, Valgrind later complains "conditional jump or move depends on uninitialised value(s)" when those variables are used. Is my understanding flawed here, or is Valgrind throwing false positives?


Solution

  • In C++ classes/structs are identical (in terms of initialization).

    A non POD struct may as well have a constructor so it can initialize members.
    If your struct is a POD then you can use an initializer.

    struct C
    {
        int x; 
        int y;
    };
    
    C  c = {0}; // Zero initialize POD
    

    Alternatively you can use the default constructor.

    C  c = C();      // Zero initialize using default constructor
    C  c{};          // Latest versions accept this syntax.
    C* c = new C();  // Zero initialize a dynamically allocated object.
    
    // Note the difference between the above and the initialize version of the constructor.
    // Note: All above comments apply to POD structures.
    C  c;            // members are random
    C* c = new C;    // members are random (more officially undefined).
    

    I believe valgrind is complaining because that is how C++ used to work. (I am not exactly sure when C++ was upgraded with the zero initialization default construction). Your best bet is to add a constructor that initializes the object (structs are allowed constructors).

    As a side note:
    A lot of beginners try to value init:

    C c(); // Unfortunately this is not a variable declaration.
    C c{}; // This syntax was added to overcome this confusion.
    
    // The correct way to do this is:
    C c = C();
    

    A quick search for the "Most Vexing Parse" will provide a better explanation than I can.