双指针中的内存泄漏 [英] Memory leak in Double pointer
本文介绍了双指针中的内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好
我正在使用类似
的结构
Hello
I am using a structure like
struct abc
{
int x;
int y;
};
struct abcArray
{
int iCount;
abc **test;
};
进一步使用like(内存分配):
Further Use this like(memory allocation):
abcArray xyz;
xyz.test = new abc*;
for(int i = 0 ; i < 10 ; i++)
xyz.test[i] = new xyz;
对于重新分配:
For deallocation:
for(int i = 0 ; i < 10 ; i++)
{
delete[] xyz.test[i];
xyz.test[i] = NULL;
}
当我检查内存泄漏时,它在
上显示泄漏
When I check for memory leaks,it says leak at
xyz.test = new abc*;
有人可以建议我如何分配以避免这种泄漏吗?
Can anybody suggest me how I should deallocate to avoid this leak?
推荐答案
abcArray xyz;
xyz.test = new abc*;
for(int i = 0 ; i < 10 ; i++)
xyz.test[i] = new xyz;
您已经为单个abc
结构分配了一个指针,然后继续访问以下不属于您的9个单元格.您应该像这样分配:
You have allocated a pointer to a single abc
structure and then proceeded to access the following 9 cells which do not belong to you. You should allocate like:
xyz.test = new abc*[10];
理查德所说的是正确的...但是有多种解决方案可用:
^ ]
^ ]
^ ]
What Richard said is correct... but there''s a variety of solutions available:
CArray (MFC)[^]
vector (STL)[^]
Linked list (there''s several implementations out there)[^]
首先,使用new
分配xyz.test[i]
,然后使用delete[]
取消分配.两者不在一起!在单个分配的对象上使用delete,仅在分配的数组上使用delete []!
另外,您分配了xyz.test,但未能取消分配它-这导致了泄漏.
你说:
但是我不确定需要分配多少个单元...将在需要时分配.我仅使用10个作为参考.随机地,我必须一一分配.
这意味着您不能将结构存储在简单的C数组中.相反,您需要一个链表.如果您不想自己实现,则应遵循Albert Holguin发布的最后一个链接.
如果您仅使用C进行编程(没有C ++构造,没有模板),请查看此
First, you allocatexyz.test[i]
usingnew
, but then you deallocate it usingdelete[]
. The two don''t go together! Use delete on singular allocated objects and delete[] only on allocated arrays!
Also, you allocate xyz.test, but fail to deallocate it - this is causing the leak.
You said:
But I am not sure how many cells need to be allocated...It is to be allocated as and when required.I used 10 just for reference.Randomly I have to allocate cell one by one.
This means you can not store your structs in a simple C array. Instead you need a linked list. You should follow the last link posted by Albert Holguin if you don''t want to implement your own.
If you are programming in C only (no C++ constructs, no templates), then check out this article about an Implementation of a single linked list in C. It has some very good explanations.
这篇关于双指针中的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文