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

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


崩溃现场,如图:


来自微软的解释(多处理器上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标准模板库的供货商。
      2.a 首先禁用引用计数;      
   enum _Mref {_FROZEN = 255}; // set to zero to disable sharing

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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值