Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Uninitialized memory?

Tags:

c++

I am sometimes (randomly) getting incorrect initialization of values, which makes me think I'm using memory uninitialized somewhere. My main data structure is:

template <class state>
class learnedStateData {
public:
    learnedStateData() :gCost(DBL_MAX), hCost(0), isDead(false) {}
    state theState;
    double gCost;
    double hCost;
    bool isDead;
};

This is being stored in a STL hash_map. Any thoughts on how I might get uninitialized data (besides the theState) from this data structure?

Let me clarify: I don't want my values to be uninitialized, but they appear to be randomly at times.

like image 495
Nathan S. Avatar asked Oct 01 '10 06:10

Nathan S.


People also ask

What is uninitialized value in C?

An uninitialized variable is a variable that has not been given a value by the program (generally through initialization or assignment). Using the value stored in an uninitialized variable will result in undefined behavior.

How do I fix C6001 C++?

C6001: using uninitialized memory <variable>This warning may be fixed by adding empty curly braces so that the variable/object is value-initialized (will be all zeros). This warning and corresponding quick fix are enabled by default in the Microsoft Native Minimum ruleset.

What value is stored in uninitialized variables in C?

The value in an uninitialized variable is one of: zero, a compiler dependent value (such as 0xCC's in visual studio), or data previously stored in that memory location (old data).


2 Answers

The implementation is perfectly sound... your issue must be elsewhere. You could use a tool like valgrind to check for invalid memory accesses, uninitialised reads etc.. You could add some assertions to try to narrow down the point where the state is corrupted. If you provide a hash algorithm, make sure it returns the same value consistently for the same key value. Check you don't somehow modify the key of an object while it's inside the container. You might swap in a std::map<> and see if the problem disappears.

like image 199
Tony Delroy Avatar answered Sep 29 '22 16:09

Tony Delroy


You have not initialized theState inside the constructor

Use Value Initialization

template <class state>
class learnedStateData {
public:
    learnedStateData() :theState(),gCost(DBL_MAX), hCost(), isDead() {}
    state theState;        ^                         ^          ^
    double gCost;          |_________________________|__________|
    double hCost;                            |
    bool isDead;                        Value Initialized
};
like image 40
Prasoon Saurav Avatar answered Sep 29 '22 15:09

Prasoon Saurav