[英]Pointer Memory Leak
我的指針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;
}
}
是! 您永遠不會釋放內存。 您應該為通過new/new[]
分配的每條內存調用delete/delete[]
new/new[]
。
是的你將會
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
通常,對new
運算符的每次調用都應與對operator delete
或delete[]
調用配對使用
是。 您必須使用new
delete
分配的每個內存。
p = new int [val+1];
p = &buff[bBreak[k]]; // here you lose track of the memory you've just allocated
如果您不想手動進行內存管理,請使用std::vector<int>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.