Search code examples
cmemory-managementcalloc

Failure of free()


If I'm allocating memory in a loop like so

for(file = 0; file < nfile; file++){
...
...
...
   for(yy = 0; yy < ngridy; yy++){
      for(xx = 0; xx < ngridx; xx++) {
         tmparr1[xx+(ngridx*yy)] = (double *)calloc(nptperf[file], sizeof(double));
         tmparr2[xx+(ngridx*yy)] = (double *)calloc(nptperf[file], sizeof(double));
      }
   }

Sometime later in the code I'm freeing memory like so :

for(yy = 0; yy < ngridy; yy++){
    for(xx = 0; xx < ngridx; xx++) {
       free(tmparr1[xx+(ngridx*yy)]);
       free(tmparr2[xx+(ngridx*yy)]);
    }
}

Would there be a possibility of free() not freeing the memory and hence causing a whole lot more memory to be allocated? I'm allocating and freeing the memory once every file loop. Also, nptperf[file] is usually around 1-3 million points, and ngridx = ngridy = 100.

This program works for ngridx = ngridy = 80 and less, but fails at 100.


Solution

  • You are using wrong variables inside the bodies of your loops (gg and ggy instead of xx and yy). Among other problems, this causes (almost) all of the allocated memory to be leaked since you're losing the calloc()ed pointers.