在C ++中使用delete删除malloc的行为 [英] Behaviour of malloc with delete in C++

查看:881
本文介绍了在C ++中使用delete删除malloc的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

delete p;

当我们使用malloc分配内存时,我们应该使用free释放它,当我们使用C ++然后我们应该使用删除。

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分配内存,然后使用删除,那么应该有一些错误。但是在上面的代码中没有C ++中出现的错误或警告。

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

此外,如果我们使用new来释放和释放,那么也没有错误或警告。

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

为什么会这样?

推荐答案

因为没有办法可靠地证明指针后面的内存被正确分配了(例如 new for delete new [] for delete [] )。这是你的工作,以确保这样的事情不会发生。当你使用正确的工具,即智能指针,它很简单。每当你说 delete ,你就做错了。

This is undefined behaviour, as there's no way to reliably prove that memory behind the pointer was allocated correctly (i.e. by new for delete or 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.

这篇关于在C ++中使用delete删除malloc的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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