unclear memory leak with vector, c++, when calling exit - c++

I was debugging my program and I've noticed that even though I've marked almost all of
it as comment and all I did was to push double values into a vector, I have a memory leak. I read the api in c++ reference, but couldn't find anything. Here's the code:
#include <vector>
#include <cstdlib>
#include <iostream>
#include "RegMatrix.h"
#include "Matrix.h"
using namespace std;
int main(void)
{
vector<double> v;
for (int i=0; i<9; i++)
{
v.push_back(i);
}
cout << endl;
exit(EXIT_SUCCESS);
}
And valgrind's report:
==9299== HEAP SUMMARY:
==9299== in use at exit: 128 bytes in 1 blocks
==9299== total heap usage: 5 allocs, 4 frees, 248 bytes allocated
==9299==
==9299== 128 bytes in 1 blocks are still reachable in loss record 1 of 1
==9299== at 0x402569A: operator new(unsigned int) (vg_replace_malloc.c:255)
==9299== by 0x804937D: __gnu_cxx::new_allocator<double>::allocate(unsigned int, void const*) (in /home/yotamoo/workspace/ex3/main)
==9299== by 0x804922F: std::_Vector_base<double, std::allocator<double> >::_M_allocate(unsigned int) (in /home/yotamoo/workspace/ex3/main)
==9299== by 0x8048E6C: std::vector<double, std::allocator<double> >::_M_insert_aux(__gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > >, double const&) (in /home/yotamoo/workspace/ex3/main)
==9299== by 0x8048CA2: std::vector<double, std::allocator<double> >::push_back(double const&) (in /home/yotamoo/workspace/ex3/main)
==9299== by 0x8048B10: main (in /home/yotamoo/workspace/ex3/main)
==9299==
==9299== LEAK SUMMARY:
==9299== definitely lost: 0 bytes in 0 blocks
==9299== indirectly lost: 0 bytes in 0 blocks
==9299== possibly lost: 0 bytes in 0 blocks
==9299== still reachable: 128 bytes in 1 blocks
==9299== suppressed: 0 bytes in 0 blocks
This is weird. Any ideas? thanks

exit() will not call the destructors of the current scope thus there may be a leak:
(§3.6.1/4) Calling the function void exit(int); declared in <cstdlib> (18.3) terminates the program without leaving the current block and hence without destroying any objects with automatic storage duration (12.4). If exit is called to end a program during the destruction of an object with static storage duration, the program has undefined behavior.
Use this instead:
#include <vector>
#include <iostream>
int main(int argc, char *argv[]) {
std::vector<double> v;
for (int i=0; i<9; i++) {
v.push_back(i);
}
std::cout << endl;
return 0;
}

The vector never goes out of scope for the exit.
Just remove the exit() from main and replace it with a return 0;

I don't believe that you have a memory leak. When valgrind says the memory is still reachable it's not telling you that it leaked but that it wasn't free'ed before the program exited. In this case the vector desctructor didn't get called before exit. Try returning from main rather than calling exit().

Did you try putting all the code except exit in a separate {} block?

You did not have to call the exit function it will immediate exit from the program did not call the OS clean up calls.
Always use the return() not exit().

Related

Memory leak while handling exceptions

I just move to C++ from C, and currently slicing my path through exceptions.
I'm having a hard time figuring out why am I getting a memory leak in this simple program:
#include <iostream> /* I/O */
#include <exception> /* exception */
#include <cstdlib> /* stdlib */
using namespace std;
void Bar()
{
throw exception();
}
void Foo()
{
int *ip = new int;
try
{
Bar();
}
catch(exception &e)
{
cerr << "Foo: Exception caught: " << e.what() << endl;
delete ip;
exit(1);
}
delete ip;
}
int main()
{
Foo();
return 0;
}
I feel like I'm missing something crucial here, but can't point at it. Any idea?
Valgrind's output:
==21857== Memcheck, a memory error detector
==21857== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==21857== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==21857== Command: ./a.out
==21857==
Foo: Exception caught: std::exception
==21857==
==21857== HEAP SUMMARY:
==21857== in use at exit: 136 bytes in 1 blocks
==21857== total heap usage: 3 allocs, 2 frees, 72,844 bytes allocated
==21857==
==21857== 136 bytes in 1 blocks are possibly lost in loss record 1 of 1
==21857== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==21857== by 0x4ECD8FF: __cxa_allocate_exception (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.25)
==21857== by 0x108CCC: Bar() (ex33.cpp:9)
==21857== by 0x108D0C: Foo() (ex33.cpp:18)
==21857== by 0x108DBD: main (ex33.cpp:31)
==21857==
==21857== LEAK SUMMARY:
==21857== definitely lost: 0 bytes in 0 blocks
==21857== indirectly lost: 0 bytes in 0 blocks
==21857== possibly lost: 136 bytes in 1 blocks
==21857== still reachable: 0 bytes in 0 blocks
==21857== suppressed: 0 bytes in 0 blocks
==21857==
==21857== For counts of detected and suppressed errors, rerun with: -v
==21857== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
You should't call exit in C++ really. Local objects destructors will not be called. And cause stack will not be unwounded, looks like destructor of exception also will not be called.
From standard:
18.1.2 When an exception is thrown, control is transferred to the nearest handler with a matching type (18.3); “nearest” means the
handler for which the compound-statement or ctor-initializer following
the try keyword was most recently entered by the thread of control and
not yet exited
18.1.3 Throwing an exception copy-initializes (11.6, 15.8) a temporary object, called the exception object. An lvalue denoting the temporary
is used to initialize the variable declared in the matching handler
(18.3). If the type of the exception object would be an incomplete
type or a pointer to an incomplete type other than cv void the program
is ill-formed.
Stack is not unwound: destructors of variables with automatic storage duration are not called. Quote from here
As it turned out, replacing exit(1) from within Foo() to return; fixed the memory leak.
So, my follow-up question, why can't I call exit() from Foo()?

std::thread causes segmentation fault in Raspbian using gcc-linaro-4.9.4

I'm getting a segmentation fault on code that looks perfectly valid to me.
Here's a minimal recreating example:
#include <iostream>
#include <thread>
void func()
{
/* do nothing; thread contents are irrelevant */
}
int main()
{
for (unsigned idx = 0; idx < 1000; idx++)
{
std::thread t(func);
void* buffer = malloc(1000);
free(buffer);
t.join();
}
return 0;
}
I made a run with prints, to check which iteration fails; I got the segmentation fault on iteration #292.
I used gcc-linaro-4.9.4 (taken from here: https://releases.linaro.org/components/toolchain/binaries/4.9-2017.01/arm-linux-gnueabihf/).
I compiled the program this way:
arm-linux-gnueabihf-g++ -std=c++11 -std=gnu++11 -lpthread -pthread main.cpp -o main.out
I tried recreating this in gcc-linaro-6.5, and didn't have the problem there.
Any idea why this happens?
Edit 1
There is no warnings/errors when I compile this code.
Running it under strace reveals nothing special.
Running it under GDB reveals that the segmentation faults happens in free function:
Thread 1 "main.out" received signal SIGSEGV, Segmentation fault.
_int_free (av=0x76d84794 <main_arena>, p=0x1e8bf, have_lock=0) at malloc.c:4043
4043 malloc.c: No such file or directory.
(gdb) bt
#0 _int_free (av=0x76d84794 <main_arena>, p=0x1e8bf, have_lock=0) at malloc.c:4043
#1 0x00010bfa in main ()
Running it under valgrind reveals the following:
==361== Thread 2:
==361== Invalid read of size 4
==361== at 0x4951D64: ??? (in /usr/lib/arm-linux-gnueabihf/libstdc++.so.6.0.22)
==361== Address 0x4becf74 is 0 bytes after a block of size 28 alloc'd
==361== at 0x4847D4C: operator new(unsigned int) (vg_replace_malloc.c:328)
==361== by 0x11629: __gnu_cxx::new_allocator<std::_Sp_counted_ptr_inplace<std::thread::_Impl<std::_Bind_simple<void (*())()> >, std::allocator<std::thread::_Impl<std::_Bind_simple<void (*())()> > >, (__gnu_cxx::_Lock_policy)2> >::allocate(unsigned int, void const*) (in /home/pi/main.out)
==361==
==361== Invalid write of size 4
==361== at 0x4951D6C: ??? (in /usr/lib/arm-linux-gnueabihf/libstdc++.so.6.0.22)
==361== Address 0x4becf74 is 0 bytes after a block of size 28 alloc'd
==361== at 0x4847D4C: operator new(unsigned int) (vg_replace_malloc.c:328)
==361== by 0x11629: __gnu_cxx::new_allocator<std::_Sp_counted_ptr_inplace<std::thread::_Impl<std::_Bind_simple<void (*())()> >, std::allocator<std::thread::_Impl<std::_Bind_simple<void (*())()> > >, (__gnu_cxx::_Lock_policy)2> >::allocate(unsigned int, void const*) (in /home/pi/main.out)
==361==
==361==
==361== HEAP SUMMARY:
==361== in use at exit: 28,000 bytes in 1,000 blocks
==361== total heap usage: 2,002 allocs, 1,002 frees, 1,048,368 bytes allocated
==361==
==361== Thread 1:
==361== 28,000 bytes in 1,000 blocks are definitely lost in loss record 1 of 1
==361== at 0x4847D4C: operator new(unsigned int) (vg_replace_malloc.c:328)
==361== by 0x11629: __gnu_cxx::new_allocator<std::_Sp_counted_ptr_inplace<std::thread::_Impl<std::_Bind_simple<void (*())()> >, std::allocator<std::thread::_Impl<std::_Bind_simple<void (*())()> > >, (__gnu_cxx::_Lock_policy)2> >::allocate(unsigned int, void const*) (in /home/pi/main.out)
==361==
==361== LEAK SUMMARY:
==361== definitely lost: 28,000 bytes in 1,000 blocks
==361== indirectly lost: 0 bytes in 0 blocks
==361== possibly lost: 0 bytes in 0 blocks
==361== still reachable: 0 bytes in 0 blocks
==361== suppressed: 0 bytes in 0 blocks
==361==
==361== For counts of detected and suppressed errors, rerun with: -v
==361== ERROR SUMMARY: 2017 errors from 3 contexts (suppressed: 6 from 3)
edit 2
I still get segmetation fault after I remove the -lpthread and -std=c++11 compilation flags. This is the way I compiled it this time:
arm-linux-gnueabihf-g++ -std=gnu++11 -pthread main.cpp -o main.out
I think the problem is a mismatch between your code and the libstdc++.so library you're linking to.
One possibility is that the wrong libstdc++.so is being used at runtime, which you could check by using the ldd utility. The correct version for GCC 4.9.4 is libstdc++.so.6.0.20 so if you see it linking to a different version, that's a problem.
The second possibility is that it's the right libstdc++.so but it is compiled with different settings from your code, and so the std::thread in your code uses atomic operations for shared_ptr reference counting, but the std::thread in the library uses a mutex (which is the same problem as described in GCC Bug 42734). If the crash and the valgrind errors go away when you compile your program with -march=armv5t then it would confirm this is the problem.

GDB: Printing value of a function argument in a memory location

I'm using Valgrind and GDB to debug a memory leak. I've the following call trace that shows where the memory leak occurs:
(gdb) monitor block_list 10104
==961== 153 (18 direct, 135 indirect) bytes in 1 blocks are definitely lost in loss record 10,104 of 10,317
==961== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==961== by 0x678199: create_node(unsigned char const*, unsigned int, document*) (a.cpp:436)
==961== by 0x67933A: insert(art_node*, art_node**, unsigned char const*, unsigned int, document*, unsigned int, int, int*) (a.cpp:704)
==961== by 0x68327B: Program::add(std::string const&) (program.cpp:84)
==961== by 0x7220BF: main (main.cpp:52)
I want to print the value of the string argument that's passed to Program::add at:
==961== by 0x68327B: Program::add(std::string const&) (program.cpp:84)
How do I do that in GDB?
You can follow step by step Valgrind manual:
If you want to debug a program with GDB when using the Memcheck tool,
start Valgrind like this:
valgrind --vgdb=yes --vgdb-error=0 prog
In another shell, start GDB:
gdb prog
Then give the following command to GDB:
(gdb) target remote | vgdb
Now you can go to frame Program::add(std::string const&) in gdb and print the value of argument.

Load shared lib in c++ causes segmentation fault

I am learning c++, and am experimenting with loading a shared lib on linux (.so).
I get a segmentation fault when I run the below code.
When I try to run the console app using valgrind, I get the following:
valgrind ./TestLoadSo --leak-check=full -v
==26828== Memcheck, a memory error detector
==26828== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==26828== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==26828== Command: ./TestLoadSo --leak-check=full -v
==26828==
!!!Hello World!!!
==26828== Jump to the invalid address stated on the next line
==26828== at 0x0: ???
==26828== by 0x53E63F0: (below main) (libc-start.c:291)
==26828== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==26828==
==26828==
==26828== Process terminating with default action of signal 11 (SIGSEGV)
==26828== Bad permissions for mapped region at address 0x0
==26828== at 0x0: ???
==26828== by 0x53E63F0: (below main) (libc-start.c:291)
==26828==
==26828== HEAP SUMMARY:
==26828== in use at exit: 3,126 bytes in 9 blocks
==26828== total heap usage: 13 allocs, 4 frees, 76,998 bytes allocated
==26828==
==26828== LEAK SUMMARY:
==26828== definitely lost: 0 bytes in 0 blocks
==26828== indirectly lost: 0 bytes in 0 blocks
==26828== possibly lost: 0 bytes in 0 blocks
==26828== still reachable: 3,126 bytes in 9 blocks
==26828== suppressed: 0 bytes in 0 blocks
==26828== Rerun with --leak-check=full to see details of leaked memory
==26828==
==26828== For counts of detected and suppressed errors, rerun with: -v
==26828== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
[1] 26828 segmentation fault (core dumped) valgrind ./TestLoadSo --leak-check=full -v
C++ Main class
extern "C" typedef char* (*helloWorld_t)();
int main() {
void* handle = dlopen("./libMyLib.dll.so", RTLD_LAZY);
if (!handle) {
cerr << "Cannot open library: " << dlerror() << '\n';
return 1;
}
helloWorld_t hello = (helloWorld_t)dlsym( handle, "helloWorld" );
const char * tmp = hello();
printf("\n%s",tmp);
return 0;
}
The extern function is:
extern "C++" char* helloWorld() {
char str[25];
strcpy(str, "HelloWorld");
}
If I use extern "C" I get a compilation error:
error: conflicting declaration of ‘char* helloWorld()’ with ‘C’ linkage
extern "C" char* helloWorld() {
Its really not clear to me where I am going wrong.
A function cannot have both C and C++ linkage, and a function pointer type must match its target function's linkage.
You cannot dlsym an extern "C++" function by its unadorned name. You have to either use extern "C" in both cases (recommended), or use extern "C++" throughout and replace the string in dlsym(handle, "helloWorld") with the mangled name of your function (not recommended).
Always check the result of dlsym and report an error if it returns a null pointer (use dlerror() like you've done for dlopen).
Don't use character arrays or pointers to represent strings. There is a type for string, called std::string.
Last but not least, always compile with -Wall -Werror so things like a non-void function that doesn't actually return a value will be caught.
Many problems here:
extern "C++" char* helloWorld() {
char str[25];
strcpy(str, "HelloWorld");
}
It should use "C" linkage. And it should return something. And it copies the string to local variable, so value gets lost when it returns. So probably
extern "C" char* helloWorld() {
static char str[25]; // will keep its value accross calls, not thread safe
return strcpy(str, "HelloWorld"); // return pointer to start of str
}
Note that multiple calls all return same static buffer. If you need copies, you need to let caller provide a buffer, or return buffer allocated with malloc.

Valgrind reports 'possibly lost' memory when working with Boost threads

I have a program that runs some action in a separate therad, then joins on the thread, such as this one:
#include <boost/thread.hpp>
#include <iostream>
using namespace std;
void f() {
for (int i = 0; i < 100; ++i) cout << i << endl;
}
int main() {
boost::thread t(f);
t.join();
return 0;
}
If I run Valgrind on it, it reports 'possibly lost' memory. This seems logical if I omit the join(), because in that case the thread is still running when the program exits. But if the thread is finished, I would expect that there are no warnings.
Here is the backtrace:
==8797== 288 bytes in 1 blocks are possibly lost in loss record 2 of 3
==8797== at 0x4A1F8B3: calloc (vg_replace_malloc.c:467)
==8797== by 0x400F289: allocate_dtv (in /lib64/ld-2.4.so)
==8797== by 0x400F34D: _dl_allocate_tls (in /lib64/ld-2.4.so)
==8797== by 0x53EF981: pthread_create##GLIBC_2.2.5 (in /lib64/libpthread-2.4.so)
==8797== by 0x4B3311D: boost::thread::start_thread() (in /home/egbomrt/BOOST/inst_1_47_0/lib/libboost_thread.so.1.47.0)
==8797== by 0x40A20C: boost::thread::thread<void (*)()>(void (*)(), boost::disable_if<boost::is_convertible<void (*&)(), boost::detail::thread_move_t<void (*)()> >, boost::thread::dummy*>::type) (thread.hpp:204)
==8797== by 0x406295: main (main.cpp:12)
Is this a problem with Boost Thread, Posix Thread or is this perfectly normal? I could just create a suppression rule for it, but it would also be good if I got a warning if there is an unfinished thread, but not when all threads are finished.
I found that the problem is with the pthread library. If I run the program on SUSE 10, I get the memory leaks, but if I run it on SUSE 11, I don't get the problem.
I get the same results with and without Boost.
Thanks for the comments. That helped me pinpoint the problem.