0

My program is reading a file (test.txt and it contains only 2 strings and a white space like : "Hello World") and when I use calloc, it gives me memory leak with using valgrind. The problem is I get more bytes lost in second mem allocation(b = calloc(11,sizeof(*b)).

I have tried to use free() it didn't work

    char str[1024];
    char *a = NULL;
    char *a = NULL;
    int i = 0;
    while(!feof(myfile)) {
       //I used some codes here to skip "\r\n" which is working fine.
       fscanf(myfile, "%10s", str);
       i = strlen(str);
       if(key_find(k,str) == NULL){
         a = calloc(i,sizeof(*a));
         strcpy(a,str);
         key_insert(k,a);
       }
       fscanf(myfile, " ");
       fscanf(myfile, "%10s", str);
       if(key_find(k,str) == NULL){
         b = calloc(i,sizeof(*a));
         strcpy(b,str);
         key_insert(k,a);
       }
    }
   free(a); free(b);

It does not give me any memory leak when I only have 2 different strings in my txt file. But if I have more than 4 strings then it gives me memory leak.

1 Answers1

0

During runtime, you need to do as many free's as you did callocs. If calloc is within the loop, free also should be within the loop, eg:

 a = calloc(i,sizeof(*a));
 strcpy(a,str);
 key_insert(k,a);
 free(a); /* you need to free a when it is not needed */

Then

 b = calloc(i,sizeof(*a));
 strcpy(b,str);
 key_insert(k,a); /* you should probably replace this by key_insert(k,b) */
 free(b); /* don't need b anymore? free it! */
user31264
  • 6,557
  • 3
  • 26
  • 40
  • in a while condition? I tried it but it gives me error "the key is not found" althoug I inserted – Kim Petterson May 25 '19 at 17:59
  • You're correct that there will eventually need to be a `free()` for each `calloc()`, and that will probably occur in _a_ loop. However, if `key_insert()` doesn't make a copy of the `a` argument, the freeing should only be done when the data structure managed by `key_insert()` is released, not in the input loop. The exact time when `free()` should be called depends on details not divulged in the question. – Jonathan Leffler May 25 '19 at 18:15
  • @JonathanLeffler yes!! I used strcpy in the function key_insert and now it works. thank you so much. – Kim Petterson May 25 '19 at 18:51