0
Light Poster
Quote:
Originally Posted by xpi0t0s
Absolutely. free(p) will free the 12 bytes that were allocated by malloc(12). sganesh, wherever you got that idea from, it's complete nonsense.

Now if you do
Code:
```int **p=malloc(12*sizeof(int*));
for (int i=0; i<12; i++)
p[i]=malloc(12*sizeof(int));```
(which creates a 2D array of 144 ints), THEN you will need a loop to free each of p[i] before you free p itself. Observe then that the malloc's exactly match the free's (there will be 13 of each). Every malloc must be matched by *exactly* one free for the application not to exhibit undefined behaviour.
I think you completely misunderstood me. free(p) will free the 12 bytes that were allocated by malloc(12) I also said that it is false. It will free only one pointer(location) that is pointed by p.
0
Go4Expert Founder
Quote:
Originally Posted by sganesh
can you tell me which is not true.

I am coming to say pointer is like an array. If you free one location it is not mean that other locations also cleared.
You told that for freeing memory you will need a loop but that is completely false. You do not need a loop
0
Mentor
You asked what parts of what you said were false. Just about every point you made was false.

> Because free will clear the first location which is pointed by p.

False. If p=malloc(x) then free(p) will free *ALL* x bytes. Not just the first.

> If you want to clear all locations that is allocated by malloc. you need to use loop you need to have the temporary pointer then freeing it then move to the next pointer.

False. If p=malloc(x) then free(p) will free *ALL* x bytes. My post suggested you may have confused this with allocating an array of pointers then individually mallocing each of those pointers. In that case, yes you will need to free each individual pointer before freeing the array of pointers. But your argument is that if p=malloc(x) then to free this you need free(p), free(p+1), free(p+2), ..., free(p+x-1) in order to free all x bytes. THIS IS FALSE. If you think it's true, what is your source? Where did you get this idea from?

> free(p) will free the 12 bytes that were allocated by malloc(12) I also said that it is false. It will free only one pointer(location) that is pointed by p.

Wrong again. If p=malloc(12) then free(p) will free *ALL* 12 bytes. You *DO NOT* need 12 calls to free().

You don't have to take it from me (a site Mentor with over 1000 posts) and shabbir (the site Admin) who both disagree with you. You can also take it from:

Wikipedia http://en.wikipedia.org/wiki/Malloc which states "free(void *pointer) ... releases the block of memory pointed to by pointer"

the Gnu documentation http://www.gnu.org/s/libc/manual/htm...er-Malloc.html

cplusplus.com: http://www.cplusplus.com/reference/c.../cstdlib/free/

It's perfectly OK that you've misunderstood something, hence my asking "where did you get this wrong idea from" so that we could perhaps help you see how you've misunderstood.