[英]Pointer Memory Leak
My pointer p is inside a function, will i get memory leak with this code. 我的指针p在一个函数内部,此代码会导致内存泄漏。
for(k=0;k< 3;k++)
{
int *p=NULL;
int val = bBreak[k+1] - bBreak[k];
p = new int [val+1];
p = &buff[bBreak[k]];
for(int i=0;i< val;i++)
{
cout<<"\n"<<p[i]<<endl;
}
}
Yes! 是! You never free the memory.
您永远不会释放内存。 You should call
delete/delete[]
for every piece of memory you allocate with new/new[]
. 您应该为通过
new/new[]
分配的每条内存调用delete/delete[]
new/new[]
。
Yes, you will 是的你将会
p = new int [val+1]; //allocate array on the heap
p = &buff[bBreak[k]]; //new allocated array is leaked because you lost the pointer to it
//and you are not able to call 'delete[]' to free the memory
Generally, every call to operator new
should be paired with call of operator delete
or delete[]
通常,对
new
运算符的每次调用都应与对operator delete
或delete[]
调用配对使用
Yes. 是。 You must
delete
every memory you allocate with new
. 您必须使用
new
delete
分配的每个内存。
p = new int [val+1];
p = &buff[bBreak[k]]; // here you lose track of the memory you've just allocated
If you don't want to do memory management by-hand, use a std::vector<int>
. 如果您不想手动进行内存管理,请使用
std::vector<int>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.