指针内存泄漏

时间:2012-08-08 08:52:20

标签: c++

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

        }

    }

3 个答案:

答案 0 :(得分:1)

是的!你永远不会释放记忆。您应该使用delete/delete[]为您分配的每个内存调用new/new[]

答案 1 :(得分:0)

是的,你会

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[]

的调用配对

答案 2 :(得分:0)

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

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

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