C ++,在for循环中分配空间,可能的内存泄漏验证 [英] C++, allocating space in a for loop, possible memory leak verification

查看:454
本文介绍了C ++,在for循环中分配空间,可能的内存泄漏验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是好奇,如果这个代码会创建多个内存泄漏,或者如果它会得到正确清理。

I was just curious as to if this code would create multiple memory leaks, or if it would get cleaned up correctly.

Node *newNode;

for (int i = 0; i < 10; i++)
{
    newNode = new Node();
}

delete newNode;

显然代码不做任何事情,但它确实帮助我解释我的情况。我分配内存10次,当我删除指针留下9孤儿?或者我是否重复使用相同的空间分配和正确删除孤儿?
提前感谢!

So obviously the code doesn't do anything, but it does help me explain my scenario. Am I allocating memory 10 times and when I'm deleting the pointer leaving 9 orphans? Or am I reusing the same space being allocated and removing the orphan correctly? Thanks in advance!

推荐答案

是的,这是泄漏的记忆。当你这样做:

Yeah this is leaking memory. When you do:

newNode = new Node();

您正在重新定义指针指向新分配的内存,

You are redefining the pointer to point to newly-allocated memory, in effect losing hold of a way by which to address the previously-pointed to memory in order to delete it.

所以当你离开循环时, newNode 指针指向最后分配的(第十)内存/ 节点。当你 delete newNode 你只删除那个内存。您不再有删除其他人的方式。

So when you leave the loop, the newNode pointer points to the last-allocated (tenth) memory/Node. When you delete newNode you are deleting only that memory. You no longer have a way by which to delete the others.

由于 Zhi Wang 指出,您可以使用某种形式的智能指针( unique_ptr shared_ptr 在C ++ 11中)。这些智能指针基本上是围绕常规指针的包装,其具有防止这种泄漏的附加语义。如果你使用其中的一个,内存/对象将在超出范围时自动释放(在这种情况下,在循环结束时)。

As Zhi Wang pointed out, you can use some form of smart pointer (unique_ptr or shared_ptr in C++11 for example). These smart pointers are basically wrappers around regular pointers which have additional semantics which prevent this kind of leak. If you used one of these, the memory/objects would automatically be deallocated when they went out of scope (upon ending of the current iteration of the for loop in that case).

,我认为这不会解决您在这种情况下的情况。我怀疑你想要创建它们后立即 delete 10个对象。相反,你可能希望将这些对象存储在一个容器中,如 std :: vector 或至少有一个指针数组指向这些分配的实例。这样,你将有对象(我相信是你想要的,因为你正在构建他们),并有一种方法,以后删除它们。

However, I don't think this would solve your situation in this case. I doubt you want to delete the 10 objects as soon as you create them. Rather, you probably want to store these objects in a container like a std::vector or at the very least have an array of pointers pointing to each of these allocated instances. That way you will have the objects around (which I believe is what you want, since you're constructing them at all) and also have a way by which to remove them later.

这篇关于C ++,在for循环中分配空间,可能的内存泄漏验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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