gpt4 book ai didi

c - Realloc 和 Valgrind

转载 作者:行者123 更新时间:2023-11-30 18:31:42 24 4
gpt4 key购买 nike

使用valgrind和realloc有什么问题吗? valgrind 似乎给了我关于内存的错误,它没有被释放,尽管我相信我释放了它应该释放的所有内容,你能帮助我吗?

/* declarations*/
typedef struct Hash_node{
char* word;
char** overflow_list;
int overlow;
} Hash_node;

Hash_node* create_Hash_node();
int assign_word(Hash_node*,char*);
void free_Hash_node(Hash_node*);

Hash_node* create_Hash_node(char* word){
Hash_node *temp=malloc(sizeof(Hash_node));
if(temp==NULL){
printf("Memory couldn't be allocated at creating hash_node\n");
return NULL;
}

temp-> word=NULL;
temp-> overflow_list=NULL;
temp->overlow=0;

return temp;
};

void free_Hash_node(Hash_node* node){
if(node->word!=NULL) free(node->word);

if(node->overlow > 0){
int i;
for(i=0; i< node->overlow;i++){
printf("%d",i);
free(node->overflow_list[i]);
}
}

free(node);
}

int assign_word(Hash_node* node,char* word){

if(word==NULL) return -1;

if(node->word==NULL){
node->word=(char*)malloc( sizeof(char)*(strlen(word)+1));
strcpy(node->word,word);

return success;
}

/*collision exists*/
if(strcmp(word,node->word)==0){
return collision;
} else{
node->overlow++;

node->overflow_list=realloc(node->overflow_list , node->overlow* sizeof(char*) );

node->overflow_list[node->overlow-1] = (char*) malloc( sizeof(char) * ( strlen(word) + 1) );
strcpy( node->overflow_list[node->overlow-1] ,word );
return collision;
}
}
int main(int argc, char** argv) {

Hash_node *a=create_Hash_node();
assign_word(a,"mpla");
assign_word(a,"hell");
assign_word(a,"kitsos2");

free_Hash_node(a);

return (EXIT_SUCCESS);
}

valgrind 在终端打印:

==12495== HEAP SUMMARY:
==12495== in use at exit: 16 bytes in 1 blocks
==12495== total heap usage: 6 allocs, 5 frees, 66 bytes allocated
==12495==
==12495== LEAK SUMMARY:
==12495== definitely lost: 16 bytes in 1 blocks
==12495== indirectly lost: 0 bytes in 0 blocks
==12495== possibly lost: 0 bytes in 0 blocks
==12495== still reachable: 0 bytes in 0 blocks
==12495== suppressed: 0 bytes in 0 blocks
==12495== Rerun with --leak-check=full to see details of leaked memory
==12495==
==12495== For counts of detected and suppressed errors, rerun with: -v
==12495== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)

最佳答案

如果我没看错,您将释放所有条目node->overflow_list[i],但不是列表本身:

free(node->overflow_list)

free_Hash_node()中。

关于c - Realloc 和 Valgrind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21075468/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com