Search code examples
c++pointersstructinitializationheap-memory

c++ pass a custom struct through a function


I have been working with this C++ program for a while, and I have figured what exactly is happening, but I haven't figured out how to fix it exactly. Here is what I have set up:

struct entry {
    string foo;
    string bar;
    string num;
};
struct node {
    entry input;
    node* left;
    node* right;
};
node* home = new node;

This code takes place in a separate header file that is included in a main cpp file, which has the following:

home->input.foo="John";
home->input.bar="Doe";
home->input.name="1234";
printAll(home);

This is were the error pops up, trying to pass home through the function printAll in the header file:

void printAll(node* start){
    if(start==NULL) return;
    printAll(start->left);
    cout << start->input.foo;
    printall(start->right);
}

The error that Visual Studio gives me is 0xCDCDCDCD on start. I understand it's not home that is causing the issue, it's start, but I don't understand how to correct this error. I read around and I can assume that start has been thrown into heap memory but it is unintalized. I didn't think this was possible. And I also can guess that C++ doesn't know what start is and how to use it, how would I correct this?


Solution

  • You haven't initialized left or right. In debug builds, Visual Studio will set uninitialized memory to 0xCDCDCDCD. This is obviously not equal to NULL, so your comparison returns false.