|
30鱼币
先上代码:(问题在红色字体部分):原码在53课时赫夫曼编码C语言实现 由于代码太多我从上面选了一部分复制下来:
- htTree * buildTree(char *inputString)
- {
-
- int * probability = (int *)malloc(sizeof(int)*256);
-
- for(int i=0; i<256; i++)
- probability[i]=0;
- for(i=0; inputString[i]!='\0'; i++)
- probability[(unsigned char) inputString[i]]++;
- pQueue * huffmanQueue;
- initPQueue(&huffmanQueue);
- for(i=0; i<256; i++)
- if(probability[i]!=0)
- {
- htNode *aux = (htNode *)malloc(sizeof(htNode));
- aux->left = NULL;
- aux->right = NULL;
- aux->symbol = (char) i;
-
- addPQueue(&huffmanQueue,aux,probability[i]);
- }
- [color=#ff0000] [/color][color=#000000]free(probability) [/color][color=#ff0000]; //我调试了程序之后发现这里为什么是每次循环都要释放一次,而不是一次就释放完成!为什么![/color]
- while(huffmanQueue->size!=1)
- {
- int priority = huffmanQueue->first->priority;
- priority+=huffmanQueue->first->next->priority;
- htNode *left = getPQueue(&huffmanQueue);
- htNode *right = getPQueue(&huffmanQueue);
- htNode *newNode = (htNode *)malloc(sizeof(htNode));
- newNode->left = left;
- newNode->right = right;
- addPQueue(&huffmanQueue,newNode,priority);
- }
- htTree *tree = (htTree *) malloc(sizeof(htTree));
- tree->root = getPQueue(&huffmanQueue);
-
- return tree;
- }
- void encode(hlTable *table, char *stringToEncode)
- {
- hlNode *traversal;
-
- printf("\nEncoding\nInput string : %s\nEncoded string : \n",stringToEncode);
- for(int i=0; stringToEncode[i]!='\0'; i++)
- {
- traversal = table->first;
- while(traversal->symbol != stringToEncode[i])
- traversal = traversal->next;
- printf("%s",traversal->code);
- }
- printf("\n");
- }
复制代码
|
最佳答案
查看完整内容
调用一次 buildTree() 函数只调用一次 free(probability); 噢,写在中间是因为后边已经不需要它了,所以赶紧释放,免得后边忘记释放导致内存泄漏。
不知道有木有充分理解哥们的问题,如有不对请继续回复。
|