在C中释放char []会产生错误,并且C编译器如何处理该char [] [英] Freeing char[] in C gives error and how do C compiler handle that char[]

查看:93
本文介绍了在C中释放char []会产生错误,并且C编译器如何处理该char []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然数组基本上是指针,但是在 C 中释放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
}

错误:nexc(4212,0x10038e3c0)malloc: *对象0x7fff5fbff54c错误:未分配要释放的指针 * 在malloc_error_break中设置一个断点以进行调试

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?

但是在 C ++ 中,编译器会给我一个编译时错误.

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
}

喜欢, Cannot delete expression of type char[12]

like, Cannot delete expression of type char[12]

我认为这是因为编译器通过在调用函数时分配并在函数结束时释放内存来处理char[12].因此,我在函数结束之前在free(ptr);之后编写了一些代码.

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("\n");
    printf("\n");
    printf("\n");
    printf("\n");
    printf("\n");
}

这仍然给出错误.这是怎么回事?

This still gives error. How is this happening?

推荐答案

您只能free使用malloc(直接或间接)或相关功能(例如realloc)分配的内容.

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

尝试传递未由malloc返回的指针将导致 未定义行为 .

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

首先,您会发现C ++中delete的编译器错误,这是因为C和C ++是具有不同规则的不同语言.

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).

这篇关于在C中释放char []会产生错误,并且C编译器如何处理该char []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆