I am having a weird problem with pointers .I am building a k-d tree for ray tracing and during the BuildKDtree function I print root->left and root->right and I get correct values for various attributes stored at node. The moment I complete that code and then try to traverse the tree using the original root's pointer the root->left and root->right values contain garbage and code crashes! Any suggestions as to what might be causing this? I could paste code if necessary but its quite clumsy.
Chances are that:
- When you allocate the datastructure for root, you're not actually getting a valid address.
- Some other code of yours (or the framework you're working with) is writing out of bounds of the structure.
Generally speaking, the second is less likely because of SEGFAULTs, but these are not guaranteed to happen unless you actually write past page boundaries. Sounds like a nasty problem for debugging, try valgrind :)
Could you check if the this pointer is valid?
Perhaps you do something like this:
Node n = 0;
n->doThat();
In this case this will not have any valid left and right pointers.
What is the signature of the BuildKDtree
function? Is it possible that somewhere there is a pointer but what actually needed is a pointer-to-pointer? Just trying to guess :)
Thanks guys for pointing out some possible conditions. I found the mistake.I was actually not allocating dynamic memory in the BuildKDtree function .So inside it every thing worked fine.But when I returned the variables were destroyed and hence the error.