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?
This question is related to
c++
struct
initialization
valgrind
calloc
You need to initialize whatever members you have in your struct, e.g.:
struct MyStruct {
private:
int someInt_;
float someFloat_;
public:
MyStruct(): someInt_(0), someFloat_(1.0) {} // Initializer list will set appropriate values
};
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
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.
Since it's a POD struct, you could always memset it to 0 - this might be the easiest way to get the fields initialized (assuming that is appropriate).
That seems to me the easiest way. Structure members can be initialized using curly braces ‘{}’. For example, following is a valid initialization.
struct Point
{
int x, y;
};
int main()
{
// A valid initialization. member x gets value 0 and y
// gets value 1. The order of declaration is followed.
struct Point p1 = {0, 1};
}
There is good information about structs in c++ - https://www.geeksforgeeks.org/structures-in-cpp/
Source: Stackoverflow.com