Reputation: 3747
I am using a 2D array, and am required to allocate it as shown:
char ** buf; //global var
void allocate()
{
buf = (char **) malloc (10 * sizeof (char*));
char * data = (char *) calloc (1, 1000);
int i;
for(i=0; i<10; i++)
buf[i] = &(data[i*100]);
}
int main()
{
allocate();
//something goes here
free(buf[0]);
free(buf);
return 0;
}
Now to free the arrays, since I cannot access the variable 'data' in main(), I cannot do free(data), hence I do free(buf[0]), assuming that I am freeing the entire array of 1000 elements. Is this the right way to do this? Does free(buf[0]) free the entire 'data' array?
(It would have been convenient to malloc every element of buf as buf[i] = malloc (100), but I cant do that since I HAVE to calloc a big block first).
Thanks in advance.
Upvotes: 1
Views: 2673
Reputation: 35540
This code is correct. The value of buf[0]
is &(data[0])
which is data
by definition. This will free all the allocated memory.
Note that if you really just want one buffer to free, you can set:
offset = 10*sizeof(char*);
buf = calloc(10*100+offset);
and in the loop do:
buf[i] = buf + offset + i*100;
Upvotes: 4
Reputation: 4423
Valgrind agrees with you. It is correct because buf[0] holds the pointer to the HEAD of the calloc'd memory block.
valgrind ./temp
==15404== Memcheck, a memory error detector
==15404== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==15404== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==15404== Command: ./temp
==15404==
==15404==
==15404== HEAP SUMMARY:
==15404== in use at exit: 0 bytes in 0 blocks
==15404== total heap usage: 2 allocs, 2 frees, 1,040 bytes allocated
==15404==
==15404== All heap blocks were freed -- no leaks are possible
==15404==
==15404== For counts of detected and suppressed errors, rerun with: -v
==15404== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 12 from 7)
Upvotes: 3
Reputation: 754010
It is slightly unusual, but it is correct. You made two allocations; you make two frees. And you release the pointers that were allocated. All should be clean.
Did you run valgrind
on your program?
Upvotes: 3