Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
912 views
in Technique[技术] by (71.8m points)

pointers - Freeing char[] in C gives error and how do C compiler handle that char[]

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You only free what you have allocated using malloc (directly or indirectly) or related function (like realloc).

Attempting to pass a pointer not returned by malloc will lead to undefined behavior.

That you get a compiler error for delete in C++ is first and foremost because C and C++ are different languages with different rules.

And remember, an array is an array, not a pointer. Though an array can decay to a pointer to its first element in many situation (like when passing it to a function).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...