-3

I have a

std::map<std::string, myClass*> myMap

then I am inserting like follow:

if(!myKey.empty())
{
    myMap[myKey] = this;
}

This sometime is throwing a segmentation fault.

Why??

Kam
  • 5,878
  • 10
  • 53
  • 97
  • 1
    You should give us this code's context. That code isolated works perfectly fine. – mfontanini Jun 28 '12 at 21:11
  • The code is huge, and from the core dump, the software always hangs at this line then goes into the map library – Kam Jun 28 '12 at 21:12
  • 1
    `myMap` might have been corrupted by some code we can't see. Have you tried debugging this? Could make it easier to determine if that's the case. – Eran Jun 28 '12 at 21:12
  • yes and the debugger exits at this line, is there a way to check if myMap is corrupted? how can it be corrupted? any example? – Kam Jun 28 '12 at 21:14
  • It might be corrupted by some erroneous low-level memory operation in which you modify an object that is declared next to it. Or, if `myMap` is a member variable, it's containing object might have been freed. Valgrind or a similar tool can also help you identify memory management issues. – Eran Jun 28 '12 at 21:29
  • I need to read more carefully. What is 'this'? – rkyser Jun 28 '12 at 21:09
  • For some reason, people are voting down on my question, I think it is very legit question?!? why so? – Kam Jun 29 '12 at 13:18

1 Answers1

1

Maybe your myMap is no longer accessible. For instance, it might be a reference to a deleted pointer, or, much more probable, a member variable of an already deleted class:

class MyClass {
  public:
    selfInsert(std::string myKey) {
      if(!myKey.empty()) {
        myMap[myKey] = this;
      }
    }

  private:
    std::map<std::string, myClass*> myMap;
}

int main()
{
  MyClass *a = new MyClass();
  delete a;
  a->selfInsert();
}
lvella
  • 12,754
  • 11
  • 54
  • 106