I've just written a function that returns a pointer to a block of memory allocated by malloc. If I call free() on the returned pointer, will this free the memory?
I tried reading up on this, but I can't find anything that says whether you can call a different pointer pointing to the same location and whether that will free all the memory or not.
This is probably majorly basic, I think I can't find the info 开发者_C百科because I'm searching for it wrong.
Any help appreciated!
Yes calling free
will free the memory. Its not the pointer that get freed but the memory that the pointer points to that is freed.
You must pass to free()
the value obtained from malloc()
.
int *x = malloc(42 * sizeof *x);
int *p = &x[0];
free(p); /* ok, same as free x; x and p have the same value */
Edit: another example
int *x = malloc(42 * sizeof *x);
for (k = 0; k < 24; k++) *x++ = 0; /* zero first 24 elements */
free(x - 24);
It's not entirely clear what you're asking here, but if what you're asking is:
Can I call free() on a pointer which points to a location within the allocated block?
then the answer is "no" -- you must pass free()
the exact pointer which you got back from malloc()
. Trying to free()
an internal pointer, or a pointer to memory which was not allocated by malloc()
, memory corruption or a crash are likely to occur.
精彩评论