free() 釋放的是 pointer 指向位於 heap 的連續記憶體,而非 pointer 本身佔有的記憶體 (*ptr)。 pointer 本身儲存在 stack 上,因此對其做 free() 會造成 error。
free(NULL)
is essentially no-operation. If p = NULL;
is missing, then the second free(p)
will cause runtime error: malloc: double free for ptr 0x130008800
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
int* p = malloc(1024);
free(p);
p = NULL;
free(p); /* error: malloc: double free for ptr 0x130008800 */
return 0;
}
the pointer is allocated on the stack but the object that pointer points to is allocated on the heap.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
int* p = malloc(1024);
free(p);
int a = 3;
p = &a;
free(p); /*error*/
return 0;
}
error: malloc: *** error for object 0x16d89b0a4: pointer being freed was not allocated