Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if a pointer returned by a function is not stored?

Tags:

c++

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);
}
like image 818
Vishal Sharma Avatar asked Jan 29 '23 14:01

Vishal Sharma


1 Answers

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.

like image 134
Bathsheba Avatar answered Feb 08 '23 22:02

Bathsheba