0

I seem to be having problems with memory allocation for a 2D array using calloc.

When allocating the 2nd dimension for the array calloc crashes when outside the IDE as a standalone executable, but works perfectly when debugging. I've gone though everything I can think of and am stumped as to why this happens; especially when it was working fine a couple of days ago. It seems to be a spontaneous malfunction that won't stop.

The code is in a seperate function of is called multiple times.

O = (double**)calloc(3*cc,sizeof(double*));
for (r = 0; r < 3*cc; r++){
    printf("Row: %d ",r);
    printf("1.Addy: %p ",&O[r]);
    O[r] = (double*)calloc(4,sizeof(double));
    printf("2.Addy: %p\n",&O[r]);
}

I've also tried using different forms of freeing the memory:

for (r = 0; r < 3*c; r++)
        free(O[r]);

&

free(O);

But they just crash at different points. As well as when the memory is not freed.

This is a screenshot of the memory addresses that it allocates during each call and they all appear to be freed and reused appropriately, but then crash. If anyone can tell me what's going on that would be the best.

Memory locations

  • 2
    Post a sscce. http://sscce.org/ – this Jan 31 '14 at 16:34
  • You should post the rest of your code, or the bare minimum to understand how the function is being called. "The code is in a seperate function of is called multiple times" is not clear enough (how many times is it called?) – ArthurChamz Jan 31 '14 at 16:40
  • This code looks ok. I think you have a problem somewhere else - perhaps an array out of bounds access is overwriting things it shouldn't and `free()` gets confused. – Filipe Gonçalves Jan 31 '14 at 16:41
  • While posting that [SSCCE](http://sscce.org), double check to make sure your properly including ``, and [get rid of the typecasts on your `calloc` calls](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858) while doing so. – WhozCraig Jan 31 '14 at 17:29

0 Answers0