4

I have been struggling with a segmentation fault for months, now I'm here to ask for help. The segmentation fault appears when I call the following function

void foo(..., std::map<MyClass*, double> & x) {
if ( !x.empty() ) x.clear();
...
}

Class A {
private:
map<MyClass*, double> _N;
public:
void f(...) {
foo(..., _N);
...
}
};

//in main routine, the function is called in a loop
A a;
while(...) {
a.f(...);
}

Using gdb, I tacked the error to the line calling the clear() function, it shows "double free or corruption" error, and the program aborts at calling c++/4.1.2/ext/new_allocator.h:94 delete(__P) which further calls free() from the gnu library /lib64/libc.so.6. But since the elements in the map are not allocated by new, why it still calls free() to clear it up. I would really appreciate your comments. Thank you.

cool machine
  • 41
  • 1
  • 3
  • The error must be elsewhere. You can call `clear()` irrespective of whether the map is empty or not anyway. Show us some more ambient code. – Kerrek SB Jul 26 '11 at 19:45
  • 1
    what happen if you pass the map by value, the program semantics would be wrong, but does it segf'? – 111111 Jul 26 '11 at 19:45
  • 1
    is the object passed as parameter to `foo` allocated on the heap ? If so, is it possible that it had already been de-allocated (or moved elsewhere) before ? – Sander De Dycker Jul 26 '11 at 19:46
  • Thank you guys. Actually the object passed to function foo is a member of another class. Here is a more complete description of my code, please take a look. – cool machine Jul 26 '11 at 19:55
  • 1
    I think we need more code than that, to me it looks ok. A should be alive at the any point where foo is called. – 111111 Jul 26 '11 at 20:09
  • Could you create a destructor for A and set a break/printf there and see if that occurs prior to segfault? – Jesse Vogt Jul 26 '11 at 20:24

2 Answers2

2

Given that the map is owned by another object it suspiciously sounds that the map-owning object was already deleted when the clear was called.

Also note that names starting with underscore and a capital letter are reserved for the implementation - you aren't allowed to use them.

Mark B
  • 95,107
  • 10
  • 109
  • 188
1

The code looks fine to me. At least with the limited context you have provided. Usually when I run into issues like this I will simply run the valgrind memcheck tool to find the place were the first "delete" happened. Once you know that, these issues can be pretty simple to solve.

Craig H
  • 7,949
  • 16
  • 49
  • 61