指针内存泄漏

Pointer Memory Leak

本文关键字:泄漏 内存 指针      更新时间:2023-10-16

我的指针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;
        }
    }

是的!您永远不会释放内存。您应该为分配的每个内存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都应与接线员deletedelete[]

是的。您必须delete使用 new 分配的每个内存。

p = new int [val+1];
p = &buff[bBreak[k]]; // here you lose track of the memory you've just allocated

如果您不想手动进行内存管理,请使用 std::vector<int>