Reputation: 325
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
Upvotes: 4
Views: 2740
Reputation: 66981
void myAllo(int mySize, char *myChar )
{ //note: myChar is a COPY of someone else's pointer
myChar = new char[mySize];
//nobody outside of the function will ever see this change
}
Dynamic memory (new) is only released when you explicitly release it.
myChar goes out of scope and is automatically cleaned up, but a pointer's "clean up" does not deallocate any memory it points at. This allows me to have multiple pointers point at the same data.
void myAllo(int mySize, char *&myChar )
{ //note: myChar is a REFERENCE of someone else's pointer
myChar = new char[mySize];
}
Or better yet, use a vector:
std::vector<char> myAllo(int mySize)
{
return std::vector<char>(mySize);
}
Upvotes: 1
Reputation: 109289
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] );
}
Upvotes: 10
Reputation: 5182
In order to get the memory you allocated you need to write the function as
void myAllo(int mySize, char **myChar )
{
*myChar = new char[mySize];
}
and call it
char* pointer;
myAllo(size, &pointer);
or as
char* myAllo(int mySize )
{
return new char[mySize];
}
and call it
char* pointer = myAllo(size);
Upvotes: 2
Reputation: 103751
Will the heap allocation be returned from myAllo() ?
No.
memory pointed by myChar will be deallocated when myAllo returns.
No, this is a memory leak.
Upvotes: 2