从堆和内存泄漏中删除C ++数组 [英] deleting c++ array from heap and memory leak

查看:90
本文介绍了从堆和内存泄漏中删除C ++数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于从堆内存中删除数组的问题.在书中和此博客和其他资源中,例如一个,我读到要从堆中删除数组,必须在 delete 关键字后使用 [] ,这样,如果我们不使用[] 我们将有泄漏内存.

I have a question regarding deleting an array from heap memory. In a book and on this blog and in other resources such as this one, I read that for removing an array from the heap we must use the [] after the delete keyword so that if we do not use [] we will have leak memory.

例如,考虑下面的代码.

for example, consider the code below.

//constructing array
int *s = new int[10];


// deleting array from heap
delete [] s;

我使用 valgrind 包在Linux上测试了这个小程序,以检查由于错误编码导致的内存泄漏量.通过Linux下的命令,我看到一切都很好

I tested this little program in Linux by using the valgrind package to check how much memory leaks we have which are caused by bad coding. By below command in Linux, I saw that everything is alright

sudo valgrind --leak-check=full ./<path_to_exe_file>

这是Linux命令的输出

this is the output of the Linux command

 ==4565== HEAP SUMMARY:
 ==4565==     in use at exit: 0 bytes in 0 blocks
 ==4565==   total heap usage: 1 allocs, 1 frees, 40 bytes allocated
 ==4565== 
 ==4565== All heap blocks were freed -- no leaks are possible

但是,当我尝试使用 delete 而不使用 [] 时,我的问题出现了. valgrind 的输出显示所有堆内存已被释放.这样对吗?或 valgrind 没意识到堆没有被释放,并且数组的某些部分还在里面!!如果 valgrind 无法检测到这种内存泄漏,是否还有其他软件包可以检测到这种情况?

However, My question arose when I tried to use the delete without using []. The output from valgrind shows that all heap memory has been freed. Is this correct? or valgrind didn't realize the heap wasn't freed and some part of the array is still in there!!? If valgrind cannot detect this kind of memory leak, is there any other package that can detect this?

推荐答案

在不使用 [] 的情况下在数组上调用 delete 会导致未定义的行为.Undefined Behavior可能是正确删除了阵列,这似乎是您观察到的.但是,您不能依靠它.

Calling delete on an array without using [] results in Undefined Behaviour. The Undefined Behaviour might be that the array is correctly deleted, which appears to be what you observed. You can't rely on this, however.

这篇关于从堆和内存泄漏中删除C ++数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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