Realloc和Valgrind

时间:2014-01-12 13:55:50

标签: c valgrind realloc

使用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)

1 个答案:

答案 0 :(得分:4)

如果我看到正确,您可以释放所有条目node->overflow_list[i], 但不是列表本身:

free(node->overflow_list)
free_Hash_node()中的