Search code examples
qtcrashcontainsqmap

Why QMap crashes, when calling contains(), in findNode function?


I have a multi threaded program that uses QMap to store some data, but it's crashing every now and then, at a very same line, when contains() function is called:

myMap.contains(a) -> keys and values are not pointers.

Crash:

#0 findNode (akey=<synthetic pointer>, this=0x120eec4c) at /var/build/workspace/stage/nto/usr/include/qt4/QtCore/qmap.h:486 #1 contains (akey=<synthetic pointer>, this=0x120eec4c) at /var/build/workspace/stage/nto/usr/include/qt4/QtCore/qmap.h:555

The line that's crashing is simply this line:

for (int i = d->topLevel; i >= 0; i--)

I believe the only thing that can cause crash is that pointer d is deleted somehow. Any idea why it is crashing, or how should I proceed with debugging?

Thanks


Solution

  • You are accessing a map instance from multiple threads without serializing the access. You cannot do that. You must either:

    1. Have a copy of the map in each thread, or

    2. Serialize access to the map with a mutex.

    Since Qt containers are implicitly shared, copying a map is rather cheap. The copy must be made in the owning thread, the copy can then be used in any other thread. The copied instance will thread-safely detach if needed.