Behaviour of malloc with delete in C++
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?
This is undefined behaviour, as there's no way to reliably prove that memory behind the pointer was allocated correctly (ie 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.
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.
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.
链接地址: http://www.djcxy.com/p/78492.html上一篇: 我可以依靠malloc返回NULL吗?
下一篇: 使用C ++删除malloc的行为