1

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

        }

    }
4

3 回答 3

1

是的!你永远不会释放内存。你应该调用delete/delete[]你分配的每一块内存new/new[]

于 2012-08-08T08:54:06.973 回答
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[]

于 2012-08-08T08:53:31.267 回答
0

Yes. You must delete every memory you allocate with new.

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>.

于 2012-08-08T09:03:27.063 回答