Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memory leak! how to fix?

Ok, so i'm just learning about memory leaks. i ran valgrind to find memory leaks. i get the following:

==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)

so does that definitively mean the leak is in my readInput function? if so, how do i get rid of the memory leaks? here's the offending function:

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()));
    }
}

thanks!

like image 244
user618712 Avatar asked Dec 05 '22 22:12

user618712


1 Answers

// ...
   return new double(atof(in.c_str()));
// ...

new acquires resource from free store which is being returned. The returned value must be deallocated using delete to avoid memory leak.


If you are calling the function in a while loop, number should be definitely deallocated using delete before running the loop next time. Just using delete once will only deallocate the very last source acquired.

Edit:

// ....

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.
}
like image 186
Mahesh Avatar answered Jan 01 '23 22:01

Mahesh