What happens if the pointer returned by the function is not saved?

There is a function that returns a pointer (any type), if I do not store a pointer when calling a function, what happens? Will the function still return a pointer in this case? If so, will there be a memory leak because I am not freeing the allocated memory?

Consider the code below as an example:

int * testfunc()
{
int * a=new int();
return(a);
}

int main()
{
testfunc();
return(0);
}
+4
source share
4 answers

Absolutely there will be a memory leak. You need to balance all calls newwith the help deleteon the returned pointer.

++ , delete: . std::unique_ptr. std::unique_ptr delete, , , .

+7

, , new, new[], malloc() calloc(). , . ++ .

+3

, .

, , , . , .

, ,

int *pi = testfunc();
delete pi;

Then when you exit the program there will be no memory leak, but yes, there is a problem with the memory leak in the function, as you requested.

+1
source

I ran valgrind in the code indicated in the question (after compiling with the '-g' option) using the operator (valgrind --leak-check=full --show-reachable=yes --track-origins=yes ./test) The output is below

==59142== Memcheck, a memory error detector
==59142== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==59142== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==59142== Command: ./test
==59142==
==59142==
==59142== HEAP SUMMARY:
==59142==     in use at exit: 4 bytes in 1 blocks
==59142==   total heap usage: 1 allocs, 0 frees, 4 bytes allocated
==59142==
==59142== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1
==59142==    at 0x4A075BC: operator new(unsigned long) (vg_replace_malloc.c:298)
==59142==    by 0x4006D3: testfunc() (test.cpp:7)
==59142==    by 0x4006EF: main (test.cpp:13)
==59142==
==59142== LEAK SUMMARY:
==59142==    definitely lost: 4 bytes in 1 blocks
==59142==    indirectly lost: 0 bytes in 0 blocks
==59142==      possibly lost: 0 bytes in 0 blocks
==59142==    still reachable: 0 bytes in 0 blocks
==59142==         suppressed: 0 bytes in 0 blocks
==59142==
==59142== For counts of detected and suppressed errors, rerun with: -v
==59142== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 6 from 6)

This clearly demonstrates that a memory leak is occurring.

-3
source

Source: https://habr.com/ru/post/1694043/


All Articles