I have a piece of code that has a struct. The purpose of this struct is to store the Huffman codes or "look up table code" used in data compression. The struct is defined as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//A Huffman tree node
struct MinHeapNode
{
char data; //Input characters
int freq; //Frequency of data
MinHeapNode *left, *right; //Left & right child
MinHeapNode(char data, int freq)
{
left = right = NULL;
this->data = data;
this->freq = freq;
}
};
Once the data gets compressed, the tree node is stored in a variable called minHeap. I tried writing this variable to a file using the following code:
fwrite((constvoid *)minHeap.top(), 1, sizeof(minHeap.top()), fDebug; and something gets written.
However, when I tried reading from it or retrieving it using the code
fread((void *)minHeap.top(), 1, sizeof(minHeap), fInput);, it failed.
//STL priority queue to store heap tree, with respect to their heap root node value.
priority_queue<MinHeapNode*, vector<MinHeapNode*>, compare> minHeap;
//Function to build the Huffman tree and store it in minHeap
void HuffmanCodes(int size)
{
struct MinHeapNode *left, *right, *top;
for(map<char, int>::iterator v=freq.begin(); v!=freq.end(); v++) {minHeap.push(new MinHeapNode(v->first, v->second));}
while(minHeap.size() != 1)
{
left = minHeap.top();
minHeap.pop();
right = minHeap.top();
minHeap.pop();
top = new MinHeapNode('$', left->freq + right->freq);
top->left = left;
top->right = right;
minHeap.push(top);
}
storeCodes(minHeap.top(), "");
}
you can't save pointers, generally. You may need to re-write this so that the left and right are indices into a vector instead of pointers.
the problem is that every time you run a program, the memory area it lives in and the memory the OS allows it to have change. Saving a pointer is saving a memory location that you have access to NOW but will not have access to NEXT RUN.
you have to watch this with pointers AND stl containers both. Anytime the thing you save is using dynamic memory you need to be careful to save the DATA pointed to, not the POINTER which is just an integer.