Kitchi
Kitchi

Reputation: 1904

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.

Upvotes: 2

Views: 126

Answers (4)

Arun Taylor
Arun Taylor

Reputation: 1572

It is possible that the program may be running out of memory, calloc returning a null, ensued by memory corruption and finally getting killed.

I would suggest checking for the return value from calloc instead of assuming that it succeeded.

If the program needs a lot memory, make sure there is enough swap space to handle the requirements. Remember that there are possibly other apps running on the system as well.

The other option is to divide and conquer. One possibility is to turn it into a distributed application running on multiple machines. Without knowing what the rest of the application does, this may or may not be feasible.

Upvotes: 0

Tim
Tim

Reputation: 1546

There are two possibilities:

  1. free() can fail meaning you don't free the memory you used (your question)
  2. your program has a bug and you don't free the memory you used, you are leaking memory.

The first is unlikely to happen, I don't know of any circumstances where free() fails if used properly. If it is passed the proper pointer, that memory will be freed, if it is passed NULL, it will do nothing.

The second is more likely to happen, but in the above snippet it looks ok. As mentioned above you can use Valgrind (/ˈvælɡrɪnd/) to check if something is going wrong. Compile with -O0 -ggdb and have Valgrind check the allocation and deallocation.

Upvotes: 1

NPE
NPE

Reputation: 500673

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.

Upvotes: 3

CCoder
CCoder

Reputation: 2335

Run a tool like Valgrind with your program and see if you are leaking any memory. From the code you have posted, it does not look like you are leaking memory. But using Valgrind will confirm that and also it can point out other problems which may exist.

Upvotes: 0

Related Questions