Why does this Deque destructor have memory leak - c++

I use doubly linked list to implement Deque in C++.
Destructor:
Deque::~Deque()
{
while (this->left_p)
{
node *temp = this->left_p;
this->left_p = this->left_p->next;
delete temp;
}
this->right_p = NULL;
}
when i use valgrind --leak-check=full ./a.out to check memory leak just to test my destructor` I got the following output:
==2636==
==2636== HEAP SUMMARY:
==2636== in use at exit: 72,704 bytes in 1 blocks
==2636== total heap usage: 1,003 allocs, 1,002 frees, 97,760 bytes allocated
==2636==
==2636== 72,704 bytes in 1 blocks are still reachable in loss record 1 of 1
==2636== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==2636== by 0x4EC3EFF: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
==2636== by 0x40106B9: call_init.part.0 (dl-init.c:72)
==2636== by 0x40107CA: call_init (dl-init.c:30)
==2636== by 0x40107CA: _dl_init (dl-init.c:120)
==2636== by 0x4000C69: ??? (in /lib/x86_64-linux-gnu/ld-2.23.so)
==2636==
==2636== LEAK SUMMARY:
==2636== definitely lost: 0 bytes in 0 blocks
==2636== indirectly lost: 0 bytes in 0 blocks
==2636== possibly lost: 0 bytes in 0 blocks
==2636== still reachable: 72,704 bytes in 1 blocks
==2636== suppressed: 0 bytes in 0 blocks
==2636==
==2636== For counts of detected and suppressed errors, rerun with: -v
==2636== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
I can't figure out why there is still ONE out of 1003 allocs not being free.
Why do i have one memory leak? what is wrong with my destructor?
Test code here:
/* Deque Test Program 6 */
#include <cstring>
#include <iostream>
#include "Deque.h"
using namespace std ;
int main (int argc, char * const argv[]) {
cout << "\n\nDeque Class Test Program 6 - START\n\n";
// Make a Deque
Deque * dq1 = new Deque();
for( int i = 0 ; i<1 ; i++ ){
dq1->push_left(1);
// dq1->display();
}
cout << "Size=" << dq1->size() << endl ;
// The destructor should delete all the nodes.
delete dq1 ;
cout << "\n\nDeque Class Test Program 6 - DONE\n\n";
return 0;
}
edit: remove implementation code.

Essentially, it's not your code's fault, it's valgrind's.
Check this other question that has had the same problem:
Valgrind: Memory still reachable with trivial program using <iostream>
Quoting from the post:
First of all: relax, it's probably not a bug, but a feature. Many implementations of the C++ standard libraries use their own memory pool allocators. Memory for quite a number of destructed objects is not immediately freed and given back to the OS, but kept in the pool(s) for later re-use. The fact that the pools are not freed at the exit of the program cause Valgrind to report this memory as still reachable. The behaviour not to free pools at the exit could be called a bug of the library though.
Hope that helps :)

The memory leak reported by valgrind does not appear to be in your code:
==2636== 72,704 bytes in 1 blocks are still reachable in loss record 1 of 1
==2636== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==2636== by 0x4EC3EFF: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
==2636== by 0x40106B9: call_init.part.0 (dl-init.c:72)
==2636== by 0x40107CA: call_init (dl-init.c:30)
==2636== by 0x40107CA: _dl_init (dl-init.c:120)
This appears to be a heap allocation from within a constructor of a global object. (In theory, it could still come from your code if operator new is called as a tail call, so that it does not show up in the backtrace, but I don't see such an object declaration in your cdoe.)
It is also not an actual leak, it is just some data allocated on the heap at program start. If you install debugging information for libstdc++, then you might get a hint of what is actually being allocated. Then you could also set a breakpoint on call_init and step through the early process initialization, to see the constructors that are called.

Related

C++ memory leak. Valgrind - mismatched delete

I receive objects from Thread #1 - its a 3rd party lib code - my callback called on it.
Objects have fixed-length string fields wrapped:
typedef struct somestr_t {
char * Data;
int Len; } somestr_t;
I have to create copy of the objects by hand every time, before I can pass it further to my code. So amongst other things I copy these strings too using this helper:
inline void CopyStr(somestr_t * dest, somestr_t * src)
{
if (src->Len == 0) {
dest->Len = 0;
return;
}
char* data = new char[src->Len];
memcpy(data, src->Data, src->Len);
dest->Data = data;
dest->Len = src->Len;
}
Then somewhere down the road I delete the object and its string fields:
if (someobj != nullptr)
{
if (someobj ->somestr.Len != 0) delete someobj ->somestr.Data;
. . .
delete someobj ;
}
When I run valgrind I get these in places where I would expect the strings to be deleted:
==33332== Mismatched free() / delete / delete []
==33332== at 0x48478DD: operator delete(void*, unsigned long) (vg_replace_malloc.c:935)
==33332== by 0x41B517: cleanup() (Recorder.cpp:86)
==33332== by 0x41BB29: signal_callback(int) (Recorder.cpp:129)
==33332== by 0x4C11DAF: ??? (in /usr/lib64/libc.so.6)
==33332== by 0x4CD14D4: clock_nanosleep##GLIBC_2.17 (clock_nanosleep.c:48)
==33332== by 0x4CD6086: nanosleep (nanosleep.c:25)
==33332== by 0x4D02DE8: usleep (usleep.c:32)
==33332== by 0x41C3EF: Logger(void*) (LogThreads.h:28)
==33332== by 0x4C5C6C9: start_thread (pthread_create.c:443)
==33332== by 0x4BFC2B3: clone (clone.S:100)
==33332== Address 0xd661260 is 0 bytes inside a block of size 12 alloc'd
==33332== at 0x484622F: operator new[](unsigned long) (vg_replace_malloc.c:640)
==33332== by 0x419E72: CopyStr (CbOverrides.h:23)
and summary report:
==34077== HEAP SUMMARY:
==34077== in use at exit: 328,520 bytes in 3,828 blocks
==34077== total heap usage: 124,774 allocs, 120,946 frees, 559,945,294 bytes allocated
==34077==
==34077== LEAK SUMMARY:
==34077== definitely lost: 0 bytes in 0 blocks
==34077== indirectly lost: 0 bytes in 0 blocks
==34077== possibly lost: 0 bytes in 0 blocks
==34077== still reachable: 328,520 bytes in 3,828 blocks
==34077== suppressed: 0 bytes in 0 blocks
I never used valgrind (or any c++ tool) before so I am not sure - why mismatch delete is reported? why there are 328K unreleased memory on exit?
char* data = new char[src->Len];
and
if (someobj ->somestr.Len != 0) delete someobj ->somestr.Data;
That delete should be delete [].
Why are there still reachable: 425,333 bytes in 3,860 blocks. Sorry, my crystal ball isn't working.
Normally Valgrind does give a hint as to what you need to do
==19283== Rerun with --leak-check=full to see details of leaked memory
It's a little bit mean in that after you've done that it will tell you about another option
==21816== Reachable blocks (those to which a pointer was found) are not shown.
==21816== To see them, rerun with: --leak-check=full --show-leak-kinds=all
Try those and start working through the non-freed memory.

throw() with clang++ shows possible memory leak

I have a piece of code, which when compiled with g++ does not show any memory leaks.
Whereas, the same when compiled with clang++ shows, possible memory leak.
Here's the trace,
==7115==
==7115== HEAP SUMMARY:
==7115== in use at exit: 16 bytes in 1 blocks
==7115== total heap usage: 2,324 allocs, 2,323 frees, 2,166,060 bytes allocated
==7115==
==7115== 16 bytes in 1 blocks are still reachable in loss record 1 of 1
==7115== at 0x4C2BFB9: calloc (vg_replace_malloc.c:762)
==7115== by 0x4129830: __cxxabiv1::__calloc_with_fallback(unsigned long, unsigned long) (in /opt/xxx/lib64/libc++abi.so.1)
==7115== by 0x4128946: __cxa_get_globals (in /opt/xxx/lib64/libc++abi.so.1)
==7115== by 0x412B287: __cxa_throw (in /opt/xxx/lib64/libc++abi.so.1)
==7115== by 0x4E712AE: Lib::GenCmd::RaiseException(Status, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >) (LibBase.cpp:291)
==7115==
==7115== LEAK SUMMARY:
==7115== definitely lost: 0 bytes in 0 blocks
==7115== indirectly lost: 0 bytes in 0 blocks
==7115== possibly lost: 0 bytes in 0 blocks
==7115== still reachable: 16 bytes in 1 blocks
==7115== suppressed: 0 bytes in 0 blocks
==7115==
==7115== For counts of detected and suppressed errors, rerun with: -v
Well, its not possible to share the code snippet, but I can tell you RaiseException() is the function where I have a call made to throw() (at line 291) an exception. Here's the function snippet:
void GenCmd::RaiseException(Status status, std::string AdditionalMsg) throw(Status) {
s_last_error = GetStatusString(status);
if (false == AdditionalMsg.empty()) {
s_last_error = s_last_error + AdditionalMsg;
}
throw(status);
}
Status is a structure, defined as below (along with default, parameterized & copy constructors)
typedef struct _Status {
const u64_t m_status : 8;
const u64_t ReservedByte1 : 8;
const u64_t m_action : 8;
const u64_t ReservedByte3 : 5;
const u64_t m_testbit1 : 1;
const u64_t m_testbit2 : 1;
const u64_t m_cmd_failure : 1;
const u64_t m_module_code : 4;
const u64_t m_file_code : 8;
const u64_t ReservedByte7 : 4;
const u64_t m_line_no : 16;
}Status
The fact, that no leaks are seen with GCC, but only with Clang makes me think this to be some issue with Clang. (With Clang, I mean it could be libcxxabi as well)
I was navigating through the source for clang, & __cxa_get_globals() is the function where a calloc() call is made. I am not yet sure of the execution flow for clang.
Any idea or any inputs which could confirm this to be a Clang issue & not my code issue?
Here's the clang version I am using. The code is compiled with C++11, additionally with '-stdlib=libc++, '-lc++', '-lc++abi'.
[user~]$ clang --version
clang version 7.1.0
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /usr/local/bin
Update: This exception is raised from the constructor.
Update
I wrote another dummy code to see the behaviour with Clang, & it seems the issue is actually with the Clang (libc++abi).
Have a look at the below naive code
#include <iostream>
#include <stdexcept>
class Positive {
int m_number1;
public:
Positive() : m_number1(10) {
}
Positive(int no) {
if (no < 0) {
// throw 100;
throw std::invalid_argument("Send positive nu");
} else {
m_number1 = no;
}
}
~Positive() {
}
void print() {
std::cout<< "Value of member is: " <<m_number1 <<std::endl;
}
};
int main() {
try {
Positive p1;
p1.print();
Positive p2(100);
p2.print();
Positive p3(-10);
p3.print();
} catch(...) {
std::cout << "Some Exception occured" <<std::endl;
}
return 0;
}
Even on executing the above code, I saw the same result on Valgrind. Here's the output:
[user]$ valgrind --leak-check=full --leak-resolution=high --show-leak-kinds=all ./a.out
==119789== Memcheck, a memory error detector
==119789== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==119789== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==119789== Command: ./a.out
==119789==
Value of member is: 10
Value of member is: 100
Some Exception occured
==119789==
==119789== HEAP SUMMARY:
==119789== in use at exit: 16 bytes in 1 blocks
==119789== total heap usage: 3 allocs, 2 frees, 201 bytes allocated
==119789==
==119789== 16 bytes in 1 blocks are still reachable in loss record 1 of 1
==119789== at 0x4C2BFB9: calloc (vg_replace_malloc.c:762)
==119789== by 0x40FF830: __cxxabiv1::__calloc_with_fallback(unsigned long, unsigned long) (in /usr/local/lib/libc++abi.so.1.0)
==119789== by 0x40FE946: __cxa_get_globals (in /usr/local/lib/libc++abi.so.1.0)
==119789== by 0x4101287: __cxa_throw (in /usr/local/lib/libc++abi.so.1.0)
==119789== by 0x4014B0: Positive::Positive(int) (in /home/user/test/a.out)
==119789== by 0x4010F9: main (in /home/user/test/a.out)
==119789==
==119789== LEAK SUMMARY:
==119789== definitely lost: 0 bytes in 0 blocks
==119789== indirectly lost: 0 bytes in 0 blocks
==119789== possibly lost: 0 bytes in 0 blocks
==119789== still reachable: 16 bytes in 1 blocks
==119789== suppressed: 0 bytes in 0 blocks
==119789==
==119789== For counts of detected and suppressed errors, rerun with: -v
==119789== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
[user]$
Interestingly, it shows 3 allocations made. Which I am assuming to be something related to the 3rd object, but how can I ensure that is cleared (or not allocated itself)?
Probably, the same thing can help me fix my original code.
I also found this problem. It actually occurs if your code throws anything at least once, so the simplest reproduction scenario is just running this code:
int
main()
{
try {
throw 42;
} catch (int) {}
}
However, if you throw several times there is still just one 16-bytes "leaked" block (which is not really leaked, since it is still reachable from some global variable). Digging into libc++abi library sources shows that such blocks are actually allocated once per thread to hold some exception processing context, and each one is freed when a thread is destroyed since it uses TLS and have proper destructor registered. So after all, it looks totally safe and is not an issue.

Memory leak detected by valgrind, but cannot find line where I forget to free [duplicate]

This question already has answers here:
PRE-2016 Valgrind: Memory still reachable with trivial program using <iostream>
(3 answers)
Closed 6 years ago.
Here is simplified version of the code, I deleted everything that doesn't concern the problem.
#include <iostream>
#define N 3
int main() {
int *input;
int **cl;
input = new int[N];
cl = new int*[N];
for(int i = 0; i < N; i++) {
cl[i] = new int[N];
}
for(int i = 0; i < N; i++) {
delete[] cl[i];
}
delete[] cl;
delete[] input;
return 0;
}
And the valgrind output:
==5782== HEAP SUMMARY:
==5782== in use at exit: 72,704 bytes in 1 blocks
==5782== total heap usage: 6 allocs, 5 frees, 72,776 bytes allocated
==5782==
==5782== 72,704 bytes in 1 blocks are still reachable in loss record 1 of 1
==5782== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==5782== by 0x4EC3EFF: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
==5782== by 0x40104E9: call_init.part.0 (dl-init.c:72)
==5782== by 0x40105FA: call_init (dl-init.c:30)
==5782== by 0x40105FA: _dl_init (dl-init.c:120)
==5782== by 0x4000CF9: ??? (in /lib/x86_64-linux-gnu/ld-2.23.so)
==5782==
==5782== LEAK SUMMARY:
==5782== definitely lost: 0 bytes in 0 blocks
==5782== indirectly lost: 0 bytes in 0 blocks
==5782== possibly lost: 0 bytes in 0 blocks
==5782== still reachable: 72,704 bytes in 1 blocks
==5782== suppressed: 0 bytes in 0 blocks
==5782==
==5782== For counts of detected and suppressed errors, rerun with: -v
==5782== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
I just started to learn C++, maybe there is some stupid error that I cannot see.
I know I should also check for example if there was no "out of memory" error when allocating, but I ignore it so that code is more clear. I also know I could use e.g. vector and don't care for the allocation, but I'm still concerned what I do wrong.
C++ provides you with tools, that encapsulate memory management for you.
#include <iostream>
#include <vector>
int main() {
// read the size for the vectors
int n;
std::cin >> n >> '\n';
// allocate vector with n elements
auto input = std::vector<int>{n};
// read the elements
for(int i = 0; i < n; i++) {
std::cin >> std::setw(1) >> input[i];
}
// print them
for(const auto& d : input) {
std::cout << d << std::endl;
}
// allocate the vectors and store 1 in each field.
auto Cl = std::vector<std::vector<int>>{n, std::vector<int>{n, 1}};
auto Cr = std::vector<std::vector<int>>{n, std::vector<int>{n, 1}};
return 0;
// will safely release all the memory here.
}
This looks a lot more like C++, and less like C. The vectors will handle all the memory management automatically for you.
Beware: I have not tested this code, so it will probably contain some bugs. I assume C++11 syntax, but it should be easy to change the code to older C++ syntax as well.
Now that you've added the valgrind output it's clearly the same issue as the one that has an answer here: Valgrind: Memory still reachable with trivial program using <iostream>
The short story is that it's not your code that causes that report. You can remove everything from main() and just return and valgrind will still give you that leak.
Read the accepted answer on that question for the explanation.

delete[] doesn't free memory according to Valgrind

I have a class unix_socket that has a double* as an attribute, and allocates memory with new in its constructor:
class unix_socket::unix_socket(){
//...
array_recvd=new double[10];
//...
}
and consequently I am using delete[] in its destructor in order to free the memory:
unix_socket::~unix_socket(){
//..
delete[] array_recvd;
//...
}
However, when using Valgrind to check for memory leaks in the program, the memory used by the array isn't freed:
==4683== HEAP SUMMARY:
==4683== in use at exit: 80 bytes in 1 blocks
==4683== total heap usage: 2 allocs, 1 frees, 648 bytes allocated
==4683==
==4683== Searching for pointers to 1 not-freed blocks
==4683== Checked 188,184 bytes
==4683==
==4683== 80 bytes in 1 blocks are still reachable in loss record 1 of 1
==4683== at 0x4C2BBA4: operator new[](unsigned long) (vg_replace_malloc.c:363)
==4683== by 0x406503: unix_socket::unix_socket() (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/client)
==4683== by 0x402355: main (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/client)
==4683==
==4683== LEAK SUMMARY:
==4683== definitely lost: 0 bytes in 0 blocks
==4683== indirectly lost: 0 bytes in 0 blocks
==4683== possibly lost: 0 bytes in 0 blocks
==4683== still reachable: 80 bytes in 1 blocks
==4683== suppressed: 0 bytes in 0 blocks
I'm sure this leak is due to the vector_recvd array_recvd, since it is only present when I have it as an attribute. What exactly am I doing wrong? How would I free the memory allocated by the array of doubles?
EDIT: So this is the main.cpp I'm using to replicate this issue:
int main () {
unix_socket client;
client.initSocket(DEFAULT_SOCKET_PATH,CLIENT_MODE);
for (int i = 0; i < 100; ++i){
client.sendVectorXd(VectorXd::Ones(30));
}
client.closeSocket();
return 0;
}
Probably relevant: this issue is only present when the socket connection is refused (no server waiting for the client).
EDIT 2: So I've found the problem, and it was indeed in initSocket(). If connecting to a socket server somehow failed (as was the case), I had exit(1):
if (connect(client_sock, (struct sockaddr *)&remote, len) == -1) {
perror("connect");
exit(1);
}
I assumed that calling exit() would call the destructors, I see now that's not the case.

Unexpected Memory Leak [Valgrind]

Today I was just trying to check how valgrind works. So I created a simple program.
//leak.C
#include<iostream>
class leak
{
int *p;
public:
leak():p(new int[10]()){std::cout<<"Constructor of leak called\n";}
virtual void set()
{
for(int i=0;i<10;++i) p[i]=i*i;
}
virtual void display()
{
std::cout<<"In leak's display()\n";
for(int i=0;i<10;++i) std::cout<<p[i]<<std::endl;
}
virtual ~leak()
{
std::cout<<"Destructor of leak called\n";
delete[] p;
}
};
class exleak: public leak
{
double *r;
public:
exleak():r(new double[5]()){std::cout<<"Constructor of exleak called\n";}
void set()
{
leak::set();
for(int i=0;i<5;i++) r[i]=i*3.0;
}
void display()
{
leak::display();
std::cout<<"In exleak's display()\n";
for(int i=0;i<5;i++) std::cout<<r[i]<<std::endl;
}
~exleak()
{
std::cout<<"Destructor of exleak called\n";
delete[] r;
}
};
int main()
{
leak *x=new exleak();
x->set();
x->display();
delete x;
}
The output was as expected. I expected no memory leak.
I compiled the file leak.C and generated an executable leak.
But when I entered the following command valgrind --leak-check=yes --verbose ./leak, I was surprised. The code had a memory leak. :-o
This is what I got.
==9320==
==9320== HEAP SUMMARY:
==9320== in use at exit: 12 bytes in 1 blocks
==9320== total heap usage: 3 allocs, 2 frees, 92 bytes allocated
==9320==
==9320== 12 bytes in 1 blocks are definitely lost in loss record 1 of 1
==9320== at 0x40263A0: operator new(unsigned int) (vg_replace_malloc.c:214)
==9320== by 0x8048B0E: main (in /home/prasoon/leak)
==9320==
==9320== LEAK SUMMARY:
==9320== definitely lost: 12 bytes in 1 blocks
==9320== indirectly lost: 0 bytes in 0 blocks
==9320== possibly lost: 0 bytes in 0 blocks
==9320== still reachable: 0 bytes in 0 blocks
==9320== suppressed: 0 bytes in 0 blocks
==9320==
==9320== For counts of detected and suppressed errors, rerun with: -v
==9320== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 25 from 6)
How is the code leaking memory?
definitely lost: 12 bytes in 1 blocks //WHERE?
EDIT : Matter Resolved.
I tried it on Linux with 2.6.18-164.11.1.el5 kernel and GCC 4.1.2, it does not give me any leak
and i don't see any issue with the code
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.10) 5.4.0 20160609
valgrind-3.11.0
do not get any warning
class exleak has no virtual destructor...