vendredi 27 novembre 2015

std::atomic: Access violation writing location 0xFEEEEFEEE in Visual Studio 2013 (VC12)

The following minimal code example compiled in Debug mode for x64 and run in the Visual Studio 2013 debugger yields an

Unhandled exception at ...: Access violation writing location 0xFEEEFEEE.

When debugging I see that the error occurs when the second thread (t2) enters UseMyAtomic(), directly at the assignment of a1 to ep1_1.

(When run from the console without debugger, the error reads "Instruction at 0x... referenced memory at 0xddddddd... The memory could not be written.").

#include <atomic>
#include <thread>
#include <string>

void UseMyAtomic( std::atomic<std::string>& a1,
  std::atomic<std::string>& a2 )
{
  std::string ep1_1 = a1;
  std::string ep1_2 = a1.load();

  std::string ep2_1 = a2;
  std::string ep2_2 = a2.load();
}

int main()
{
  std::atomic<std::string> a1("127.0.0.1:41001");
  std::atomic<std::string> a2("127.0.0.1:41002");
  std::thread t1( [&a1, &a2](){
    UseMyAtomic( a1, a2 );
  } );
  std::thread t2( [&a1, &a2](){
    UseMyAtomic( a2, a1 );
  } );
  t1.join();
  t2.join();

  return 0;
}

When I remove the "direct assignments" (i.e., std::string epX_1 = aX), it fails with a different message in VS debugger:

Debug Assertion Failed!

File: f:\dd\vctools\crt\crtw32\misc\dbgdel.cpp

Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

Aucun commentaire:

Enregistrer un commentaire