Reputation: 35
What would cause a pointer to look like this in c++? I'm building a Huffman Tree for a project and my program is segfaulting when this is one of the child nodes of the current node. This doesn't get detected by childNode == NULL
either.
(TreeNode *) 0x3130303030313131
Edit, the below functions are being called in the following order: buildTree() -> generateCodes()
void HuffTree::buildTree(MinHeap * heap) {
while (heap->getSize() > 1) {
TreeNode * n1 = heap->removeMin();
TreeNode * n2 = heap->removeMin();
TreeNode * p = new TreeNode(0, (n1 != NULL ? n1->getFrequency() : 0) + (n2 != NULL ? n2->getFrequency() : 0));
p->join(n1, n2);
heap->insert(p);
}
root = heap->removeMin();
}
void HuffTree::generateCodesRecursive(TreeNode * node, int right, string code) {
if (node == NULL) return;
if (node->isLeafNode()) {
codes[node->getVal()] = code;
cout << (unsigned int) node->getVal() << " " << (int) node->getFrequency() << " " << code << endl;
}
generateCodesRecursive(node->getLeft(), 0, code + "1");
generateCodesRecursive(node->getRight(), 0, code + "0");
}
void HuffTree::generateCodes() {
generateCodesRecursive(root, 0, "");
}
Edit, heap functions:
void MinHeap::insert(TreeNode * val) {
nodes.push_back(val);
int index = nodes.size() -1 ;
while (nodes[parent(index)]->getFrequency() > nodes[index]->getFrequency()){
swapNodes(index, parent(index));
index = parent(index);
}
}
TreeNode * MinHeap::removeMin() {
if (nodes.size() == 0) return NULL;
TreeNode* minNode = nodes[0];
if (nodes.size() > 0){
TreeNode* lastNode = nodes[nodes.size()-1];
nodes.pop_back();
nodes[0] = lastNode;
}
int index = 0;
while((left(index) < nodes.size() && nodes[left(index)]->getFrequency() < nodes[index]->getFrequency()) ||
(right(index) < nodes.size() && nodes[right(index)]->getFrequency() < nodes[index]->getFrequency())) {
int swapIndex = right(index) >= nodes.size() ? left(index) : (nodes[left(index)]->getFrequency() <= nodes[right(index)]->getFrequency() ? left(index) : right(index));
swapNodes(swapIndex, index);
index = swapIndex;
}
return minNode;
}
Upvotes: 0
Views: 91
Reputation: 325
Couple of things to keep in mind. When you do TreeNode* p;
p
won't be null and will point to garbage memory, which won't be detected by if (p == NULL)
or if (p == nullptr)
conditions unless you explicitly set it to null
during initialization.
Also, are you initializing the internal data member of TreeNode in it's constructor properly?
Upvotes: 2
Reputation: 58848
You would get such an invalid pointer value if you have some data that is not a pointer and you try to pretend it's a pointer.
The most likely way you would obtain such a pointer is from an uninitialized pointer variable. In C and C++, uninitialized variables - including pointers - may contain unpredictable "random garbage" values.
Upvotes: 1