Although arrays are basically pointers, freeing char[]
in C gives an error.
#include <stdlib.h>
int main(void) {
char ptr[] = "Hello World";
free(ptr); // this gives error at run time
}
ERROR: nexc(4212,0x10038e3c0) malloc: * error for object 0x7fff5fbff54c: pointer being freed was not allocated
* set a breakpoint in malloc_error_break to debug
The interesting part is that, it is saying I am freeing a pointer which is not allocated.
How could this happen?
But in C++, compiler gives me a compile time error instead.
int main(void) {
char ptr[] = "Hello World";
delete ptr; // this gives error at compile time
}
like,
Cannot delete expression of type char[12]
I thought this is because of compiler handles the char[12]
by allocating when the function is called and deallocating the memory when the function ends. So, I write some codes after free(ptr);
before the function ends.
#include <stdlib.h>
int main(void) {
char ptr[] = "Hello World";
free(ptr); // this still gives error at run time
printf("
");
printf("
");
printf("
");
printf("
");
printf("
");
}
This still gives error. How is this happening?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…