FIX: Access violation with std::map::erase or std::set::erase in a multithreaded application (281446)



The information in this article applies to:

  • The C Run-Time (CRT), when used with:
    • Microsoft Visual C++, 32-bit Editions 6.0 SP4

This article was previously published under Q281446

SYMPTOMS

When you call the std::map::erase and std::set::erase member functions at the same time from multiple threads, an access violation may be generated.

STATUS

Microsoft has confirmed that this is a bug in the Microsoft products that are listed in the "Applies to" section.

This bug has been fixed in Microsoft Visual Studio 6.0 Service Pack 5 (SP5).

To download the latest service pack for Visual Studio, visit the Visual Studio Product Updates page at the following Microsoft Web site:

MORE INFORMATION

The bug was introduced in Visual Studio 6.0 Service Pack 4 (SP4) when the bug that is documented in Q248477 was corrected:

For more information, click the following article number to view the article in the Microsoft Knowledge Base:

248477 FIX: Two threads may deadlock when you use the STL map or set in a multithreaded application

Steps to Reproduce Behavior

The following sample code demonstrates the bug:
// Test.cpp
// Compiler option needed: /MT or /MD
#include <windows.h>
#include <set>

typedef std::set<int> TestSet;

DWORD WINAPI Worker( LPVOID )
{
TestSet set;
int g_cIters =4;

    for( int i=0; i < g_cIters; i++ )
    {
        int r = rand();
        int j;

        for( j=0; j < r; j++ )
        {
        set.insert( j );
        }

        for( j=0; j < r; j++ )
        {
            TestSet::iterator it = set.find( j );
            set.erase( it );
        }
    } 

    return 0;
}     
      
void main()
{
   
    int cThreads = 10;

    HANDLE  aThreads[10];

    for( int i=0; i < cThreads; i++ )
    {
        aThreads[i] = CreateThread( NULL, 0, Worker, NULL, 0, NULL );
    }

    WaitForMultipleObjects( cThreads, aThreads, TRUE, INFINITE );
} 
				

Modification Type:MinorLast Reviewed:7/5/2006
Keywords:kbbug kbCPPonly kbfix kbSTL kbVC600fix kbVS600sp5fix KB281446