How to Track Down a "Double Free or Corruption" Error

how can i know from where double free or corruption (out) error is coming?

You are not observing the rule of 5: If you manually define any of the five special member functions (destructor, copy constructor, move constructor, copy assignment, move assignment), you should define all five explicitly because the auto-generated ones are most likely wrong.

This is exactly the case here:

Your class has an implicitly-defined copy constructor (which copies the pointer member). You invoke this copy constructor when you call WEIGHT_TYPE Second(Graph<WEIGHT_TYPE> _graph) - the argument is copied. Now you have two copies of the same Graph, both with a pointer to the same array of vector. The one that goes out of scope first (at the end of Second) will delete[] that pointer... But eventually the program ends, the Graph in main will go out of scope and will delete[] the pointer again! That's a double free.

This is why you should aim to follow the rule of zero: Never do explicit resource management. Don't use new and delete, use smart pointers or container classes. The compiler will auto-generate the correct operations (and forbid those that make no sense - if your class has explicit ownership of a pointer, i.e. std::unique_ptr, it cannot be copied).

Further reading: https://en.cppreference.com/w/cpp/language/rule_of_three

Why am I getting this memory access error 'double free or corruption'?

It looks like you are trying to free memory that has already been freed or was dereferenced.

Link your program with efence or run it with valgrind.

This will tell you where your pointer gets dereferenced.

Understanding 'double free or corruption' error

Double free is exactly what it means :

int *a = new int;
delete a;
delete a;

For corruption something like :

int *a = new int[10];
a++;
delete a;

This message is generated by glibc when an app request to free some memory that was already freed, or the address does not correspond to an address obtained at allocation time.

Why am I getting double free or corruption with the following code?

You're doing this:

 a = b; // a now points to the same thing as b does

...

free(a);
free(b);

... which is semantically equivalent to

free(b);
free(b);

That's the double free - b gets free'd twice - and that is disallowed in C.


For your memory leaking problem:

When you're setting a = b you're losing the original value of a. a was a pointer to the memory that you allocated with int *a = malloc(sizeof(int)); that is now lost. You need to save that address and pass it to free() before exit, if you want valgrind to stop complaining about leaks.

For each address that malloc() returns (except zero... ^_^), you should call free() with that very same address as argument.



Related Topics



Leave a reply



Submit