std::map<K, V>.clear() crashes in corrupted double-linked list

745 views Asked by At

So i got the variable

std::map<std::string, std::shared_ptr<MyClass>> m_map;

During the program shutdown routine, I'd like to exploit the wonderful smart pointer property which should (if I'm not wrong) take care of the destruction of MyClass instances, once their own last reference is destroyed.

So I'm just calling m_map.clear(), but this

  1. SOMETIME produces the aforementioned

    corrupted double-linked list
    
  2. while in other cases (unknown thus uncontrolled variable) works correctly,

  3. and finally in other cases (controlled variable; in facts, different program configuration) produces

    terminate called after throwing an instance of 'std::runtime_error*'
    

I'd gladly receive at least some hint on approaches to the problem. Since the program is strongly multithreaded (and I know very little of it) I'm wondering if the deletion of that pointer to MyClass instance would interfere with something else.

1

There are 1 answers

0
Yochai Timmer On BEST ANSWER

This type of error is caused when you're calling at least 2 methods that affect the structure from at least 2 different threads.

For example, calling clear() on std::map will change the structure of the map itself (remove all items). And if you have another thread that's using that map at the same time (IE. looping over it, inserting, etc.) then you'll have the exception you're seeing.
The exception is caused because the std::map structure is in an invalid state (map nodes are in the middle of changing positions) while you're trying to access it.

The simplest solution would be to hold a lock whenever you access that map object.