There's a function which returns a pointer(any type), if I don't store the pointer when I call the function, what happens? Will the function still return a pointer in this case? If yes, then will there be a memory leak because I'm not freeing up the allocated memory?
Consider the below code as an example:
int * testfunc()
{
int * a=new int();
return(a);
}
int main()
{
testfunc();
return(0);
}
There absolutely will be a memory leak. You need to balance all calls to new
with a delete
on the returned pointer.
C++ gives you some class to help you manage that delete
: see std::unique_ptr
. Essentially the destructor of std::unique_ptr
calls delete
which, more often than not, is extremely useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With