From e1b2fa79aeb50530fb6ffad008f43432fd1b332d Mon Sep 17 00:00:00 2001 From: Yevhen Kozirovskyi Date: Sun, 19 Jan 2025 17:53:01 +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 | 34 +++++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/sk1/compressor.c b/sk1/compressor.c index b51b200..f418523 100644 --- a/sk1/compressor.c +++ b/sk1/compressor.c @@ -45,9 +45,9 @@ void swapMinHeapNode(struct MinHeapNode** a, struct MinHeapNode** b) { // MinHeapify function void minHeapify(struct MinHeap* minHeap, int idx) { - int smallest = idx; - int left = 2 * idx + 1; - int right = 2 * idx + 2; + unsigned smallest = idx; // Преобразуем в unsigned + unsigned left = 2 * idx + 1; // Преобразуем в unsigned + unsigned right = 2 * idx + 2; // Преобразуем в unsigned if (left < minHeap->size && minHeap->array[left]->freq < minHeap->array[smallest]->freq) smallest = left; @@ -154,6 +154,25 @@ void storeCodes(struct MinHeapNode* root, char** codes, char* currentCode, int t } // Updated compressFile function +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); + } + if (root->right) { + currentCode[top] = '1'; + storeCodes(root->right, codes, currentCode, top + 1); + } + if (!(root->left) && !(root->right)) { + currentCode[top] = '\0'; + codes[root->data] = (char*)malloc(strlen(currentCode) + 1); // Use malloc instead of strdup + strcpy(codes[root->data], currentCode); // Copy the string + } +} + +// Исправление для minHeap в compressFile int compressFile(const char* input_file_name, const char* output_file_name) { FILE* inputFile = fopen(input_file_name, "rb"); if (!inputFile) { @@ -180,6 +199,7 @@ int compressFile(const char* input_file_name, const char* output_file_name) { } } + struct MinHeap* minHeap = createAndBuildMinHeap(data, frequencies, size); // Создаем кучу struct MinHeapNode* root = buildHuffmanTree(data, frequencies, size); char* codes[256] = {0}; char currentCode[MAX_TREE_HT] = {0}; // Initialize to avoid garbage values @@ -223,12 +243,8 @@ 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]); - } - freeHuffmanCodes(codes); // Освободите память для кодов - freeMinHeap(minHeap); // Освободите память для кучи + freeMinHeap(minHeap); // Free the min heap memory + freeHuffmanCodes(codes); // Free Huffman codes return 0; }