内存泄漏!怎么修?

use*_*712 4 c++ valgrind memory-leaks

好的,所以我只是在了解内存泄漏.我跑valgrind找到内存泄漏.我得到以下内容:

==6134== 24 bytes in 3 blocks are definitely lost in loss record 4 of 4
==6134==    at 0x4026351: operator new(unsigned int) (vg_replace_malloc.c:255)
==6134==    by 0x8048B74: readInput(char&) (in calc)
Run Code Online (Sandbox Code Playgroud)

那么这肯定意味着泄漏是在我的readInput函数中吗?如果是这样,我如何摆脱内存泄漏?这是违规的功能:

double* readInput(char& command){
    std::string in;
    std::getline(std::cin, in);

    if(!isNumber(in)){
        if(in.length()>1){
            command = 0;
        }
        else{
            command = in.c_str()[0];
        }
        return NULL;
    }
    else{
        return new double(atof(in.c_str()));
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Mah*_*esh 11

// ...
   return new double(atof(in.c_str()));
// ...
Run Code Online (Sandbox Code Playgroud)

new从正在返回的免费商店获取资源.必须使用deallocated返回值delete以避免内存泄漏.


如果你在while循环中调用函数,number那么在delete下次运行循环之前应该使用它来进行释放.只使用delete一次将只取消分配最后获得的源.

编辑:

// ....

while( condition1 )
{
     double *number = NULL ;
     number = readInput(command) ;

     if( condition2 )
     { .... }
     else
     { .... }

     delete number ;  // Should be done inside the loop itself.
                      // readInput either returns NULL or a valid memory location.
                      // delete can be called on a NULL pointer.
}
Run Code Online (Sandbox Code Playgroud)