Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

heap allocation returned from a function

The function has a problem: 

void myAllo(int mySize, char *myChar )
{
    myChar = new char[mySize];
}

Will the heap allocation be returned from myAllo() ? I do not think so, because memory pointed by myChar will be deallocated when myAllo returns.

Right ?

Any comments are welcome.

Thanks

like image 901
dtustudy68 Avatar asked Dec 10 '22 05:12

dtustudy68


1 Answers

Will the heap allocation be returned from myAllo() ?

No. The argument myChar is being passed by value to myAllo(), so you're simply modifying a local copy of the pointer, not the value of the pointer in the caller's context.

memory pointed by myChar will be deallocated when myAllo returns.

No again. The function leaks the allocated memory when it exits. To de-allocate memory you need to call delete[] on the pointer returned by new[] but this pointer goes out of scope when the function exits.


There are several ways to fix your problem.

Have the caller pass in the address of the pointer which will point to the allocated memory, now you can modify what the caller's pointer points to.

void myAllo(int mySize, char **myChar )
{
    *myChar = new char[mySize];
}

Similarly, your function could accept a mutable reference to the pointer

void myAllo(int mySize, char *& myChar )
{
    myChar = new char[mySize];
}

Return a pointer to the allocated memory

char *myAllo( int mySize )
{
    return new char[mySize];
}

Better than all of the above solutions, instead of returning raw pointers, return a smart pointer

std::unique_ptr<char[]> myAllo( int mySize )
{
    return std::unique_ptr<char[]>( new char[mySize] );
}
like image 136
Praetorian Avatar answered Dec 11 '22 17:12

Praetorian