Proper way to initialize C++ structs
Solution 1
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.
Solution 2
From what you've told us it does appear to be a false positive in valgrind. The new
syntax with ()
should value-initialize the object, assuming it is POD.
Is it possible that some subpart of your struct isn't actually POD and that's preventing the expected initialization? Are you able to simplify your code into a postable example that still flags the valgrind error?
Alternately perhaps your compiler doesn't actually value-initialize POD structures.
In any case probably the simplest solution is to write constructor(s) as needed for the struct/subparts.
Solution 3
I write some test code:
#include <string>
#include <iostream>
#include <stdio.h>
using namespace std;
struct sc {
int x;
string y;
int* z;
};
int main(int argc, char** argv)
{
int* r = new int[128];
for(int i = 0; i < 128; i++ ) {
r[i] = i+32;
}
cout << r[100] << endl;
delete r;
sc* a = new sc;
sc* aa = new sc[2];
sc* b = new sc();
sc* ba = new sc[2]();
cout << "az:" << a->z << endl;
cout << "bz:" << b->z << endl;
cout << "a:" << a->x << " y" << a->y << "end" << endl;
cout << "b:" << b->x << " y" << b->y << "end" <<endl;
cout << "aa:" << aa->x << " y" << aa->y << "end" <<endl;
cout << "ba:" << ba->x << " y" << ba->y << "end" <<endl;
}
g++ compile and run:
./a.out
132
az:0x2b0000002a
bz:0
a:854191480 yend
b:0 yend
aa:854190968 yend
ba:0 yend
KC3BZU
Updated on January 27, 2020Comments
-
KC3BZU over 4 years
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?
-
Erik about 13 yearsWhether it's a struct or a class has nothing to do with the ability to memset or create a constructor. See e.g. stackoverflow.com/questions/2750270/c-c-struct-vs-class
-
Scott C Wilson about 13 yearsYou wouldn't normally memset a class after creating it, since its constructor (presumably) did the initialization.
-
KC3BZU about 13 yearsIn this case I'm not using a class, but a struct.
-
Marc Mutz - mmutz about 13 yearsthere's no difference between "class" and "struct" in C++, except for the default protection (private and public, resp.). A struct can be a non-POD and a class can be a POD, these concepts are orthogonal.
-
ralphtheninja about 13 yearsA struct is a class. Edited my post :)
-
Alan Stokes about 13 yearsYou don't need to do this for a POD
-
Marc Mutz - mmutz about 13 yearsDo you have a reference for this zero-initialising of variables in C++? Last I heard, it still has the same behaviour as C. IIRC, the MSVC compiler even dropped zero-initialising uninitialised members at some point (for performance reasons, I assume), which apparently created rather severe problems for the other MS divisions :)
-
Martin York about 13 years@mmutz: You mean the
C c = {0};
-
Marc Mutz - mmutz about 13 yearsno, the
C()
, but it seems you are right. -
Scott C Wilson about 13 years@mmutz and @Erik - agreed - shortened my answer to prevent confusion.
-
Johannes Schaub - litb about 13 yearsWith a POD class,
T
,T()
has always zero initialized the scalar subobjects. The name of the toplevel initialization was called different in C++98 than in C++03 ("default initialization" vs "value initialization"), but the end effect for PODs are the same. Both C++98 and C++03 would have all values in it be zero. -
Nils over 11 yearsmemset() is not the best option, you can zero-initialize a POD struct by just calling its default ctor.
-
yanpas almost 8 yearsHow to call default ctor in this manner for
struct sigaction
from#include <signal.h>
POSIX? this struct has the same name as function sigaction -
Martin York almost 8 years@yanpas As this is a C class it has no constructor. It can either be value initialized or zero-initialized. You can also use the original C syntax for initializing a structure.
struct sigaction actionObject = {func, other1, other2};
-
yanpas almost 8 yearsIf it is C class and has no ctor will calling it's default constructor zero initialize it?
-
Martin York almost 8 years@yanpas It has no constructor to call. So you can not call the default constructor. BUT zero initialization is a specific initialization mode of objects described by the standard. It happens under very specific situations (as described above). Though I will give you that it looks exactly like a default constructor call.
-
kevinarpe about 7 yearsCan you show the recommended syntax to pass a zero-initialized POD as a function argument? Unsure, but maybe...
(C){0}
, but the "cast to type C" looks weird. -
krlmlr almost 7 yearsIf the struct has more than one element,
C c = { 0 }
triggers a warning with-Wextra
, unlikeC c = {}
. The latter is also specified in the standard: en.cppreference.com/w/cpp/language/zero_initialization. -
MattR over 6 years@yanpas I think the relevant section of the standard is [dcl.init.list] (list item 3.4)
-
Horia almost 6 years@MartinYork, I am confused by your last code snippet and attached statements. Isn't
C c();
actually a direct initialization on the stack using the default constructor with no parameters? WhereasC c = C()
is called copy-initialization? Please check this question which explains the two types of initializations. Can you please explain "Unfortunately this is not a variable declaration." in a comment or by modifying your answer? -
Martin York almost 6 years@RockyRaccoon
C c();
unfortunately is not a variable declaration but rather a forward declaration of a function (A function called 'c' that takes no parameters and returns an object of type C). Google: Most Vexing Parse -
Martin York almost 6 years@RockyRaccoon The declaration
C c = C()
is not actually a copy-initialization (though it does look like one (and I also originally (and incorrectly) though of it that way; I thought he compiler was just smart enough to optimize out the copy so you never saw the copy). BUT this is explicitly called out in the standard as a construction only. -
Martin York almost 6 years@RockyRaccoon The difference here and with the question you link to in your comment; is that in this case there are no parameters used in the construtor. So the compiler has a hard time parsing this and telling the difference between variable declaration and forward declaration of a function. It chooses forward function declaration. If you require a parameter in the constructor then the compiler can see this is a variable declaration without any issues.
C c(4);
Is a valid variable declaration. -
Horia almost 6 years@MartinYork, thanks for the replies. I understand the issue now. I also read the 'Most vexing parse' wiki. In light of these - do you think that copy-initialization should always be used when initializing local objects, since it is not prone to these errors (traps)? I also understand that copy-initialization does not do extra operations of calling the extra copy constructor - since it is optimized by the compiler most of the times, unless you disable copy-elision (G++
-fno-elide-constructors
flag). -
Martin York almost 6 years@RockyRaccoon This is why
{}
initialization was added to the language.C c{};
is unambiguous and does what you expect. -
Horia almost 6 years@MartinYork, this is still not unambiguous as you need to aware of classes which implement an initializer_list constructor - then it is prioritised over the other constructors and does not behave as using the older syntax:
std::vector<int> v1(3, 0);
andstd::vector<int> v2 = std::vector<int>(3, 0);
result in vectors with three 0 elements each whilestd::vector<int> v3{ 3, 0 };
andstd::vector<int> v4 = std::vector<int>{ 3, 0 };
will initialize vectors with two elements, 3 and 0. So is there another method which is really sound? -
Martin York almost 6 years@RockyRaccoon You are confusing your constructors. This question is only about default construction. Sure your class may overide the constructor with
std:: initializer_list
but an empty initializer list and a default constructor (you would hope) do logically the same thing. But that is why we also have code review. -
nycynik about 5 yearsOk, I'm not so familiar with
new sc;
vsnew sc();
. I would have thought the missing parens was an error. But this seems to demonstrate that the answer is correct (it does init to 0 when you use the default constructor.) -
user over 3 yearsHow does a struct have private members?
-
ralphtheninja over 3 yearsWhat do you mean how? By adding private in front of them, just like a normal class.