C++ leaks in case of exception even by using smart pointers - c++

I am new to the smart pointers world. I've done my reading and all of them stated that smart pointers will avoid leaking memory even when the program will exit after encountering an exception.
I wrote down a simple program to try this out, but Valgrind is telling me my program is leaking memory (three allocs and only one free).
This is the source code:
#include <iostream>
#include <memory>
using namespace std;
int main()
{
auto_ptr<int> ptr_int(new int(5));
throw std::bad_alloc();
cout << *ptr_int;
}
And this Valgrind report:
==27862== Memcheck, a memory error detector
==27862== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
==27862== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==27862== Command: ./smart_pointers
==27862== Parent PID: 5388
==27862==
==27862==
==27862== HEAP SUMMARY:
==27862== in use at exit: 104 bytes in 2 blocks
==27862== total heap usage: 3 allocs, 1 frees, 120 bytes allocated
==27862==
==27862== 4 bytes in 1 blocks are still reachable in loss record 1 of 2
==27862== at 0x4026351: operator new(unsigned int) (vg_replace_malloc.c:255)
==27862== by 0x804878A: main (smart_pointers.cpp:8)
==27862==
==27862== 100 bytes in 1 blocks are possibly lost in loss record 2 of 2
==27862== at 0x4025BD3: malloc (vg_replace_malloc.c:236)
==27862== by 0x40E861A: __cxa_allocate_exception (in /usr/lib/libstdc++.so.6.0.14)
==27862== by 0x80487AE: main (smart_pointers.cpp:10)
==27862==
==27862== LEAK SUMMARY:
==27862== definitely lost: 0 bytes in 0 blocks
==27862== indirectly lost: 0 bytes in 0 blocks
==27862== possibly lost: 100 bytes in 1 blocks
==27862== still reachable: 4 bytes in 1 blocks
==27862== suppressed: 0 bytes in 0 blocks
==27862==
==27862== For counts of detected and suppressed errors, rerun with: -v
==27862== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 19 from 8)
Does using smart pointers guarantee the allocated resources will be destroyed even if an exception shows up?

If an exception is not handled, then it's implementation-defined whether the stack will be unwound before calling std::terminate.
If you handle the exception, then the smart pointer will work as expected.
Reference:
C++11 15.5.1 The std::terminate() function
1 In some situations exception handling must be abandoned for less subtle error handling techniques. These situations are:
........
— when the exception handling mechanism cannot find a handler for a thrown exception , or
........
2 In such cases std::terminate() is called. In the situation where no matching handler is found, it is implementation-defined whether or not the stack is unwound before std::terminate() is called.

When std::terminate() is called (as is the case for an uncaught exception), normal cleanup is not run (at least for the stack-frame of main()), and as such the memory you've allocated in that stack frame leaks, even though it's supposedly managed by a smart-pointer. When you're catching the std::bad_alloc in main(), and return normally, the smart-pointer will do it's duty.

If the exception is not caught, then the stack unwinding is implementation specific. Therefore in your case, it does not release the memory.
Also, auto_ptr is no longer recommended.
Use std::unique_ptr :
unique_ptr<int> ptr_int(new int(5));

Related

Why does Valgrind not report any issue after not freeing malloc'd memory?

I'm trying to figure out why Valgrind does not emit any warning even if, in the following piece of code, there is no free after the malloc:
#include "stdlib.h"
#include "string.h"
char* ptr;
int main (int argc, char *argv[]) {
ptr = static_cast<char*>(malloc(5 * sizeof(char)));
strcpy(ptr, "test");
}
Is there some kind of "automatic free" I'm not aware of or am I missing something else?
Thanks.
It does report the issue, but to see it you need to run Valgrind with --leak-check=full --show-leak-kinds=all options:
$ valgrind --leak-check=full --show-leak-kinds=all ./a.out
==317235== Memcheck, a memory error detector
==317235== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==317235== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==317235== Command: ./a.out
==317235==
==317235==
==317235== HEAP SUMMARY:
==317235== in use at exit: 5 bytes in 1 blocks
==317235== total heap usage: 2 allocs, 1 frees, 72,709 bytes allocated
==317235==
==317235== 5 bytes in 1 blocks are still reachable in loss record 1 of 1
==317235== at 0x483980B: malloc (vg_replace_malloc.c:309)
==317235== by 0x40113E: main (1.cpp:7)
==317235==
==317235== LEAK SUMMARY:
==317235== definitely lost: 0 bytes in 0 blocks
==317235== indirectly lost: 0 bytes in 0 blocks
==317235== possibly lost: 0 bytes in 0 blocks
==317235== still reachable: 5 bytes in 1 blocks
==317235== suppressed: 0 bytes in 0 blocks
==317235==
==317235== For lists of detected and suppressed errors, rerun with: -s
==317235== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
Even if you run Valgrind without any options you can see the issue in HEAP SUMMARY section:
==317235== in use at exit: 5 bytes in 1 blocks
but without any more details.
A memory leak means the loss of a pointer value to allocated memory. Once the value has been lost, it is no longer possible to release the memory.
The lifetime of a static pointer is the the entire execution of the process. Thus the pointer value was never lost, because it was always stored, and at no point of the program is there a situation where the pointer couldn't be freed.
Valgrind documentation classifies such memory as:
"Still reachable". This covers cases 1 and 2 (for the BBB blocks) above. A start-pointer or chain of start-pointers to the block is found. Since the block is still pointed at, the programmer could, at least in principle, have freed it before program exit. "Still reachable" blocks are very common and arguably not a problem. So, by default, Memcheck won't report such blocks individually.
Is there some kind of "automatic free"
Not in the sense of a call to free, but once a program stops, it no longer exists and its allocations are of no concern.

Valgrind detects unfreed heap memory usage for a trivial code

My valgrind is telling me that it found non-freed heap memory for the most trivial C++ code.
My code is shown as follows:
#include <iostream>
#include <string>
int main() {
std::cout << "Hello!!!!" << std::endl;
return 0;
}
And the result of valgrind is here:
==12455== HEAP SUMMARY:
==12455== in use at exit: 72,704 bytes in 1 blocks
==12455== total heap usage: 2 allocs, 1 frees, 73,728 bytes allocated
==12455==
==12455== 72,704 bytes in 1 blocks are still reachable in loss record 1 of 1
==12455== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==12455== by 0x4EC3EFF: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
==12455== by 0x40106C9: call_init.part.0 (dl-init.c:72)
==12455== by 0x40107DA: call_init (dl-init.c:30)
==12455== by 0x40107DA: _dl_init (dl-init.c:120)
==12455== by 0x4000C69: ??? (in /lib/x86_64-linux-gnu/ld-2.23.so)
==12455==
==12455== LEAK SUMMARY:
==12455== definitely lost: 0 bytes in 0 blocks
==12455== indirectly lost: 0 bytes in 0 blocks
==12455== possibly lost: 0 bytes in 0 blocks
==12455== still reachable: 72,704 bytes in 1 blocks
==12455== suppressed: 0 bytes in 0 blocks
==12455==
==12455== For counts of detected and suppressed errors, rerun with: -v
==12455== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
Is this a bug of valgrind?
This is due to the way the C++ standard library works. The containers allocate chunks of memory (called pools) and manage them internally. They use basically a memory manager of their own, rather than relying on system's memory manager. Therefore, when an object is destroyed, it's memory is freed by the internal allocator for reuse, but not given back to the operating system.
This is also described in valgrind's FAQ here.
To generalize a bit more, valgrind is a very useful tool, but you should not aim for 0 leaks, but rather to understand its reports and find leaks that indicate a problem in the code.
I use valgrind 3.14.0 under Ubuntu 19.04 and i dont get any detections. I ran with --leak-check=fulland without. Maybe its just some versions of valgrind.

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

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.
Yes, you have to manually free every block of memory allocated with new, new[], malloc() and calloc(). The method will still return a pointer and it's pointing to valid memory but you can't use or free it. In C++ you should nearly always return by value and move semantics will take care of dynamic memory.
Yes, it does leak memory.
The pointer variable in function scope will get destroyed when the function exit, but the data the pointer has allocated will remain in memory.
The function return the address of where the data is located.
If this is really what your function is intended to do, then you can still delete the data with the returned address
int *pi = testfunc();
delete pi;
Then there won't be a memory leak when your program exit, but yes there is a memory leak in the function as you have asked.
I ran valgrind on the code given in the question(after compiling it with '-g' option) using the statement(valgrind --leak-check=full --show-reachable=yes --track-origins=yes ./test)
Below is the output
==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 there is a memory leak.

use signal handler to release resources?

I wrote a socket server. And I realize when I hit Ctrl-C while it's running, there's some possible memory leak. I used valgrind to find this.
My server code is quite simple. Basically I create a Listener object, start a thread to accept connections and try to join that thread:
try {
Server::Listener listener(1234);
boost::thread l(boost::bind(&Server::Listener::start, &listener));
l.join();
} catch(exception& e) {
cout<<e.what()<<endl;
}
When I run valgrind, it give me:
==3580== Command: bin/Debug/p_rpc
==3580==
Listner started ...
in loop..
^C==3580==
==3580== HEAP SUMMARY:
==3580== in use at exit: 3,176 bytes in 24 blocks
==3580== total heap usage: 28 allocs, 4 frees, 4,328 bytes allocated
==3580==
==3580== 288 bytes in 1 blocks are possibly lost in loss record 21 of 24
==3580== at 0x4C29E46: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3580== by 0x4012084: _dl_allocate_tls (dl-tls.c:297)
==3580== by 0x4E3AABC: pthread_create##GLIBC_2.2.5 (allocatestack.c:571)
==3580== by 0x5260F9F: boost::thread::start_thread() (in /usr/lib/libboost_thread.so.1.49.0)
==3580== by 0x407B93: boost::thread::thread, boost::_bi::list1 > > >(boost::_bi::bind_t, boost::_bi::list1 > >&&) (thread.hpp:171)
==3580== by 0x404CA4: main (main.cpp:179)
==3580==
==3580== LEAK SUMMARY:
==3580== definitely lost: 0 bytes in 0 blocks
==3580== indirectly lost: 0 bytes in 0 blocks
==3580== possibly lost: 288 bytes in 1 blocks
==3580== still reachable: 2,888 bytes in 23 blocks
==3580== suppressed: 0 bytes in 0 blocks
==3580== Reachable blocks (those to which a pointer was found) are not shown.
==3580== To see them, rerun with: --leak-check=full --show-reachable=yes
==3580==
==3580== For counts of detected and suppressed errors, rerun with: -v
==3580== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 2 from 2)
Killed
It points out there's 288bytes possibly lost. I imagine I could use a signal handler to release this resourse. But I don't know how I do that. Can you give me an example please?
Cheers,
Elton
When a process closes, the OS automatically cleans up all memory owned by the process. You don't need to worry about freeing that memory when the program exits. The building is being demolished. Don't bother sweeping the floor and emptying the trash cans and erasing the whiteboards. And don't line up at the exit to the building so everybody can move their in/out magnet to out. All you're doing is making the demolition team wait for you to finish these pointless housecleaning tasks.
The kind of leaks you do need to worry about are those that continuously leak during the program's lifetime.
In principle, you can destroy the object there. There are restrictions on what you can do in a signal handler, and they mix very badly with threads. Note that in this area the compiler can do no (or very little) checking, the signal handler is just an ordinary function. Be extra careful.
The answers to this question give some details on how to do it.

Boost thread Leakage C++

Could someone let me know whether boost thread library leaks. It seems to me that it does:
Google says that I should compile with both boost thread and pthread which I am doing and that in version 1.40 this problem has been fixed but I still get leakage. Note that this will compile fine but leaks are detected.
#include <boost/thread.hpp>
#include <boost/date_time.hpp>
void t1(){}
int main(void){
boost::thread th1(t1);
th1.join();
return 1;
}
With Valgrind I get the following output
HEAP SUMMARY:
==8209== in use at exit: 8 bytes in 1 blocks
==8209== total heap usage: 5 allocs, 4 frees, 388 bytes allocated
==8209==
==8209== 8 bytes in 1 blocks are still reachable in loss record 1 of 1
==8209== at 0x4024F20: malloc (vg_replace_malloc.c:236)
==8209== by 0x4038CCB: boost::detail::get_once_per_thread_epoch() (in /usr/local/lib/libboost_thread.so.1.42.0)
==8209== by 0x40329D4: ??? (in /usr/local/lib/libboost_thread.so.1.42.0)
==8209== by 0x4032B26: boost::detail::get_current_thread_data() (in /usr/local/lib/libboost_thread.so.1.42.0)
==8209== by 0x4033F32: boost::thread::join() (in /usr/local/lib/libboost_thread.so.1.42.0)
==8209== by 0x804E7C3: main (testboost.cpp)
==8209==
==8209== LEAK SUMMARY:
==8209== definitely lost: 0 bytes in 0 blocks
==8209== indirectly lost: 0 bytes in 0 blocks
==8209== possibly lost: 0 bytes in 0 blocks
==8209== still reachable: 8 bytes in 1 blocks
==8209== suppressed: 0 bytes in 0 blocks
I also tried with the code listed at the following website: http://antonym.org/2009/05/threading-with-boost---part-i-creating-threads.html
Still the same problem.
This is in relation to boost 1_46_1, so it may not be true for the version that you are using. Look at the boost sources if you really want to convince yourself. (The leak detector on OSX does not detect any leaks when I run your example code).
This is not an actual leak (unless there is a bug with either pthreads, the outdated version of boost that you are using, or your compiler).
get_once_per_thread_epoch mallocs a new uintmax_t and maps it into thread-local-storage with a epoch_tss_key that has an associated destructor that frees the mapped data. Therefore the malloced memory is guaranteed to be freed.
I really don't understand why valgrind is detecting this as a leak, but it may be because the the pthreads exit functions are executing at some point after the valgrind ones. The other possibility is that the pthread functions themselves are leaking, but I didn't see anything in the documentation that would suggest that this is the case.