Question

Is there any problem using valgrind and realloc? It seems that the valgrind gives me errors about memory that it is not freed although I believe that I free everything it should be freed can you help me?

/* 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);
}

The valgrind prints at terminal:

==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)
Était-ce utile?

La solution

If I see it correctly, you free all entries node->overflow_list[i], but not the list itself:

free(node->overflow_list)

in free_Hash_node().

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top