Behaviour of malloc with delete in C++

自闭症网瘾萝莉.ら 提交于 2019-11-26 11:20:30

问题


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.

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

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

Why is it so?


回答1:


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.




回答2:


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 undefined they 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.

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




回答3:


Use free() not delete.

if you malloc you then have to call free to free memory.

if you new you have to call delete to free memory.

Here is a link that explains it.



来源:https://stackoverflow.com/questions/10854210/behaviour-of-malloc-with-delete-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!