0

温度 = p_long; 显示内存泄漏。我不确定它是如何内存泄漏的。

long *temp = NULL; 
for (int i = 1; i < 10; i++) {
  if (i < 3) {
     long *p_long = new long;

     if ( p_long ) {
        if ( 0 == *p_long ) {
           flag = true;
        } else if ( 1 == *p_long ) {
           temp = p_long;                    -----> showing memory leak here
           continue;
        }
     }
  }
}

if (temp)
delete temp;

谢谢。

4

3 回答 3

2

您没有释放堆分配long *p_long = new long;考虑到它是一个for循环,您将孤立一些内存块(newed,但没有指针再为delete-ion 引用它们。)

如果没有分配给 .你必须p_long在循环的适当部分释放它temp。您的continue陈述是多余的(也许您的意思是break?)。此外,现代版本NULLnullptr.

另一点是,您的if ( p_long )检查基本上只适用NULL于您当前new的该类型 ( long) 的堆分配器有分配问题(例如内存不足)的情况,并且以下if ( 0 == *p_long )检查新分配long的是否自动初始化的值0。AFAIK 情况并非如此,因为在 C++ 中,您只需为所需的性能付费。该值是未定义的(实际上它可能是该内存地址上现有的、未篡改的值)。

于 2013-05-28T09:32:03.670 回答
0

First time when you enter the for loop temp is NULL but in later iterations, you allocate dynamic memory to the pointer.

long *p_long = new long;

And in some iterations you just overwrite the address contained in the pointer. You lose track of the memory allocated using new. This does not mean it will automatically get freed. The memory is still allocated, just that you lost the pointer to it.

temp = p_long;     

You need something like,

else if ( 1 == *p_long ) 
{
     delete temp; -----> leaked memory freed here. 
     temp = p_long;                   
continue;
}

This will delete the allocated memory before you assign a new allocated memory address to temp.

Note: delete is safe to use on NULL too

于 2013-05-28T09:42:37.587 回答
0
long *temp = NULL; 
for (int i = 1; i < 10; i++) {
  if (i < 3) {
     long *p_long = new long;

     if ( p_long ) {
        if ( 0 == *p_long ) {
           flag = true;
        } else if ( 1 == *p_long ) {
           if(temp)
              delete temp; -----> leaked memory freed here
           temp = p_long;                   
           continue;
        }
     }
  }
}
于 2013-05-28T09:33:37.760 回答