diff --git a/sk1/compressor.c b/sk1/compressor.c index 3429d0d..10db640 100644 --- a/sk1/compressor.c +++ b/sk1/compressor.c @@ -104,6 +104,16 @@ struct MinHeap* createAndBuildMinHeap(unsigned char data[], int freq[], int size } // Build Huffman Tree +void freeHuffmanTree(struct MinHeapNode* root) { + if (root == NULL) { + return; + } + freeHuffmanTree(root->left); + freeHuffmanTree(root->right); + free(root); +} + +// Build Huffman Tree with memory management struct MinHeapNode* buildHuffmanTree(unsigned char data[], int freq[], int size) { struct MinHeapNode *left, *right, *top; struct MinHeap* minHeap = createAndBuildMinHeap(data, freq, size); @@ -112,13 +122,22 @@ struct MinHeapNode* buildHuffmanTree(unsigned char data[], int freq[], int size) left = extractMin(minHeap); right = extractMin(minHeap); + // Create a new internal node with frequency equal to the sum of the two nodes top = createNode('$', left->freq + right->freq); top->left = left; top->right = right; insertMinHeap(minHeap, top); } - return extractMin(minHeap); + + // Extract the final node, which is the root of the Huffman tree + struct MinHeapNode* root = extractMin(minHeap); + + // Free the MinHeap structure + free(minHeap->array); + free(minHeap); + + return root; } // Print Huffman Codes to a map @@ -134,7 +153,7 @@ void storeCodes(struct MinHeapNode* root, char** codes, char* currentCode, int t if (!(root->left) && !(root->right)) { currentCode[top] = '\0'; if (root->data < 256) { // Ensure data is within bounds - codes[root->data] = strdup(currentCode); + codes[root->data] = strdup(currentCode); } } }