vc6程序异常崩溃 - stl的basic_string内存破坏

内存非法写入造成内存损坏,这样的bug很难排查,因为内存破坏的地方和程序崩溃的地方相去很远,代码上很难看出关联性。


崩溃现场,如图:

vc6程序异常崩溃 - stl的basic_string内存破坏_第1张图片

来自微软的解释(多处理器上basic_string引用计数机制不正确,导致内存被破坏,ms坑跌啊):

http://support.microsoft.com/kb/813810/en-us?fr=1

STL std::string class causes crashes and memory corruption on multi-processor machines

When you build applications in Microsoft Visual C++ 6.0 that use the supplied Standard Template Library (STL), memory corruption may occur, or your computer may stop responding. These symptoms occur more frequently on multi-processor computers. Previously, the same code may have worked without such issues on a single-processor computer. When you examine the faulting thread in a debugger, you typically see the failure in a memory management function. Frequently you see the basic_string<char...> class methods in the stack trace. Because memory corruption is also a symptom, failures may appear in areas that are unrelated to string processing.

The Standard Template Library (STL) that is included with Microsoft Visual C++ 6.0 is not safe for multi-threaded applications. In particular, the implementations of the std::string class depend on the basic_string<...> template class.The basic_string<...> template class reference counts copies of a hidden character buffer. The basic_string<...> template class stores the count in an 8-bit unsigned char. The following general issues occur after this implementation:
  • The basic_string<...> template class does not protect the counting mechanism with the synchronization that is required for threads on multi-processor computers to run at the same time.(貌似和整数的原子读写有关的知识需要补充一下啊) Multi-threaded STL code that is running on single-processor computers avoids this issue because only one thread runs at a time, and memory reads or writes on integers are completed before another thread can interrupt.
  • Writing to an std::string class in one thread can corrupt the reading of a copy of the std::string class, such as one created by assignment, in another thread. The supposed copy shares the same hidden character buffer.
  • String corruption may occur where a pointer or reference to an std::string class is shared between threads. Typically, it is the responsibility of the programmer to avoid this situation.

解决方法:

1,升级到更新的visual studio版本,比如vc7(vs2003)。

2,按照该网址的做法一个一个修改(hotfix),它是微软vc6标准模板库的供货商。
      http://www.dinkumware.com/vc_fixes.html。
      2.a 首先禁用引用计数;      
   enum _Mref {_FROZEN = 255}; // set to zero to disable sharing

      2.b 静态链接(/MT)重新编译,或者动态链接(需要修改编译宏定义,参照微软给出的步骤,此处略去).


你可能感兴趣的:(vc6程序异常崩溃 - stl的basic_string内存破坏)