C++ 中带有删除的 malloc 的行为

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10854210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:32:46  来源:igfitidea点击:

Behaviour of malloc with delete in C++

c++mallocdelete-operator

提问by Luv

int *p=(int * )malloc(sizeof(int));

delete p;

When we allocate memory using malloc then we should release it using free and when we allocate using new in C++ then we should release it using delete.

当我们使用 malloc 分配内存时,我们应该使用 free 释放它,当我们在 C++ 中使用 new 分配时,我们应该使用 delete 释放它。

But if we allocate memory using malloc and then use delete, then there should be some error. But in the above code there's no error or warning coming in C++.

但是如果我们使用malloc分配内存,然后使用delete,那么应该会出现一些错误。但是在上面的代码中,C++ 中没有错误或警告。

Also if we reverse and allocate using new and release using free, then also there's no error or warning.

此外,如果我们使用 new 进行反向和分配,并使用 free 释放,那么也不会出现错误或警告。

Why is it so?

为什么会这样?

回答by Cat Plus Plus

This is undefined behaviour, as there's no way to reliably prove that memory behind the pointer was allocated correctly (i.e. by newfor deleteor new[]for delete[]). It's your job to ensure things like that don't happen. It's simple when you use right tools, namely smart pointers. Whenever you say delete, you're doing it wrong.

这是未定义的行为,因为无法可靠地证明指针后面的内存已正确分配(即通过newfordeletenew[]for delete[])。确保此类事情不会发生是您的工作。当您使用正确的工具(即智能指针)时,这很简单。每当你说delete,你就做错了。

回答by n. 'pronouns' m.

then there should be some error

那么应该有一些错误

There is. It is just not necessarily apparent.

有。它只是不一定很明显。

The C++ standard (and the C standard, on which the C++ standard is modeled) call this kind of error undefined behavior. By undefinedthey mean that anything at all may happen. The program may continue normally, it may crash immediately, it may produce a well-defined error message and exit gracefully, it may start exhibiting random errors at some time after the actual undefined behavior event, or invoke nasal demons.

C++ 标准(以及 C++ 标准所基于的 C 标准)将这种错误称为未定义行为。通过不确定他们的意思是什么都可能发生。程序可能会正常继续,可能会立即崩溃,可能会产生明确定义的错误消息并正常退出,可能会在实际未定义行为事件发生后的某个时间开始显示随机错误,或者调用鼻恶魔

It is your responsibility to watch out and eliminate these errors. Nothing is guaranteed to alert you when they happen.

您有责任注意并消除这些错误。当它们发生时,没有什么可以保证提醒您。

回答by andre

Use free()not delete.

使用free()delete

if you mallocyou then have to call freeto free memory.

如果你那么malloc你必须打电话free来释放内存。

if you newyou have to call deleteto free memory.

如果你new必须调用delete释放内存。

Hereis a link that explains it.

是一个解释它的链接。