From 7830f11bdf046cd83b375bc52a60265884cda0e4 Mon Sep 17 00:00:00 2001 From: Yevhen Kozirovskyi Date: Sun, 19 Jan 2025 17:43:47 +0000 Subject: [PATCH] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20sk1/compressor.c?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sk1/compressor.c | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/sk1/compressor.c b/sk1/compressor.c index b7c6c43..7a2482f 100644 --- a/sk1/compressor.c +++ b/sk1/compressor.c @@ -123,6 +123,8 @@ struct MinHeapNode* buildHuffmanTree(unsigned char data[], int freq[], int size) // Print Huffman Codes to a map void storeCodes(struct MinHeapNode* root, char** codes, char* currentCode, int top) { + if (!root) return; + if (root->left) { currentCode[top] = '0'; storeCodes(root->left, codes, currentCode, top + 1); @@ -133,11 +135,11 @@ void storeCodes(struct MinHeapNode* root, char** codes, char* currentCode, int t } if (!(root->left) && !(root->right)) { currentCode[top] = '\0'; - codes[root->data] = strdup(currentCode); + codes[root->data] = strdup(currentCode); // Ensure memory is allocated } } -// Compress the input file using Huffman Coding +// Updated compressFile function int compressFile(const char* input_file_name, const char* output_file_name) { FILE* inputFile = fopen(input_file_name, "rb"); if (!inputFile) { @@ -166,7 +168,7 @@ int compressFile(const char* input_file_name, const char* output_file_name) { struct MinHeapNode* root = buildHuffmanTree(data, frequencies, size); char* codes[256] = {0}; - char currentCode[MAX_TREE_HT]; + char currentCode[MAX_TREE_HT] = {0}; // Initialize to avoid garbage values storeCodes(root, codes, currentCode, 0); FILE* outputFile = fopen(output_file_name, "wb"); @@ -183,6 +185,12 @@ int compressFile(const char* input_file_name, const char* output_file_name) { int bitCount = 0; while (fread(&buffer, sizeof(unsigned char), 1, inputFile)) { char* code = codes[buffer]; + if (!code) { + fprintf(stderr, "Error: Undefined code for byte %u\n", buffer); + fclose(inputFile); + fclose(outputFile); + return -1; + } for (int i = 0; code[i] != '\0'; i++) { byte = (byte << 1) | (code[i] - '0'); bitCount++; @@ -200,9 +208,15 @@ int compressFile(const char* input_file_name, const char* output_file_name) { fclose(inputFile); fclose(outputFile); + + // Free memory for codes + for (int i = 0; i < 256; i++) { + if (codes[i]) free(codes[i]); + } return 0; } + // Decompress the file int decompressFile(const char* input_file_name, const char* output_file_name) { FILE* inputFile = fopen(input_file_name, "rb");