内存泄漏在代码中的某处

此代码适用于包含1000个单词的txt,但是当我使用10000个单词时,它会停止响应。

另外,当我使用动态数组而不是二叉树时,main.c使用10000个单词。 所以我认为问题出在tree.c代码中…

tree.h中

#ifndef TREE_H_ #define TREE_H_ typedef struct Item{ char* key; int no; } TItem; typedef struct No{ TItem item; struct No* pLeft; struct No* pRight; } TNo; void TTree_Insert (TNo**, char[]); void TTree_Print (TNo*); #endif 

tree.c

 #include  #include  #include  #include "tree.h" TNo* TNo_Create (char* c){ TNo* pNo = malloc(sizeof(TNo)); pNo->item.key = malloc(sizeof(char)*strlen(c)); strcpy(pNo->item.key, c); pNo->item.no = 1; pNo->pLeft = NULL; pNo->pRight = NULL; return pNo; } void TTree_Insert (TNo** pRoot, char word[80]){ char* c = malloc(sizeof(char)*strlen(word)); strcpy(c, word); TNo** pAux; pAux = pRoot; while (*pAux != NULL){ if (strcmp(c, (*pAux)->item.key) pLeft); else if (strcmp(c, (*pAux)->item.key) > 0) pAux = &((*pAux)->pRight); else{ (*pAux)->item.no++; return; } } *pAux = TNo_Create(c); return; } void TTree_Print (TNo *p){ if (p == NULL) return; TTree_Print (p->pLeft); printf("%s - %d", p->item.key, p->item.no); TTree_Print (p->pRight); } 

main.c中

 #include  #include  #include  #include  #include "tree.h" int main(){ TNo* pRoot = NULL; FILE* txt = fopen("Loremipsum.txt", "r"); char aux[80]; int c, x = 0; while ((c = fgetc(txt)) != EOF){ while (!(isalpha((char)c))) c = fgetc(txt); while (isalpha((char)c)) { if (isupper((char)c)) c = c+32; if (islower((char)c)) aux[x++] = (char)c; c = fgetc(txt); } aux[x] = '\0'; TTree_Insert(&pRoot, aux); x = 0; aux[0] = '\0'; } TTree_Print(pRoot); fclose(txt); return 0; } 

除了你的拼写错误(你忘了在malloc中添加1(sizeof(char)* strlen(word));)你的程序中有内存泄漏。

您已经分配了指针c指向的内存。 所以在函数TNo_Create你不需要重新分配内存。

如果找到具有给定密钥的节点,则在函数TTree_Print中也存在内存泄漏。

function可以通过以下方式查看

 static TNo* TNo_Create( char* c ) { TNo* pNo = malloc( sizeof( TNo ) ); pNo->item.key = c; pNo->item.no = 1; pNo->pLeft = NULL; pNo->pRight = NULL; return pNo; } void TTree_Insert ( TNo** pRoot, const char word[80] ) { TNo** pAux = pRoot; while ( *pAux != NULL ) { if ( strcmp( word, (*pAux)->item.key) < 0) pAux = &(*pAux)->pLeft; else if (strcmp( word, (*pAux)->item.key) > 0) pAux = &(*pAux)->pRight; else{ (*pAux)->item.no++; return; } } char* c = malloc( strlen( word ) + 1 ); strcpy(c, word); *pAux = TNo_Create(c); } 

您还可以检查malloc是否成功。