从堆中删除数组 [英] deleting array from heap

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

问题描述

我的问题是关于从堆内存中删除数组.我读了一本书,并且此博客和其他资源像这样的,并且所有人都说要从堆中删除数组,我们必须在delete函数之后使用[],因此,如果我们在不使用[]的情况下编写代码,则会导致内存泄漏.

My question is about deleting an array from heap memory. I read a book and this blog and other resources like this one, and all of them said that for deleting an array from heap we must use the [] after the delete function so if we write our codes without using [] then we have leaked memory.

例如,考虑下面的程序

int *s = new int[10];
delete [] s;

我使用valgrind软件包在Linux上测试了这个小程序(该软件包可以检查由于错误编码而产生的泄漏内存).通过在Linux中执行以下命令,我们发现一切正常

I tested this little program in Linux by using the valgrind package(this package could check how much leaked memory produces by bad coding).By below command in Linux, we saw that everything is alright

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

这是Linux命令的输出

here is the output of 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无法检测到这种泄漏的内存,那么是否有任何软件包可以检测到这种情况.

But MY question appeared when I try to use the delete without using [] and when I check the output of valgrind i saw all heap memory is freed so is it correct? or valgrind didn't know the whole heap isn't freed and some part of the array still is in there!!?? and if valgrind couldn't detect this kind of leaked memory so is there any package that can detect that.

推荐答案

在不使用[]的情况下在数组上调用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.

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

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