Search code examples
c++bonjour

Heap Corruption while Reading/Writing custom Map in multithreaded application


I have my customize Map Class

template <class TKey, class TVal> class CLSimpleMap{};


typedef CLSimpleMap<DNSServiceRef/* Descriptor*/,int/*socket*/> ClientSocketMap;                    

I am Enumerating the Wifi Device using Bonjour Api.

I have Two Thread

Main thread:

  1. Adding Decriptor and Socket in the map ClientSocketMap when Bonjour api callback return socket and descriptor for processing.
  2. I am deleting the entry when socket doesn't have data to receive

Callback Processing Thread:

  1. I am doing select to check socket has something and then pushing the Bonjour callback.

  2. I am using Crtical section to perform the addition and deletion on ClientSocketMap

But to my surprise it showing Heap corruption on Callback Processing Thread when it tries to Index the Descriptor ClientSocketMap .

I dont Understand ,Why I am getting this error.Is this due to thread? Help me to resolve the problem.


Solution

  • Check operator==() in DNSServiceRef implementation Also this class implementation based on array and every time you add new element some old elements will be moved. Maybe you use old pointers. After each "add" your's pointers invalidated

    MSDN: Each key and value pair added causes the mapping array memory to be freed and reallocated, in order to ensure the data for each is always stored contiguously.