一次vector析构异常的思考

关键字:exe、dll、STL string、local heap。

  一个结构体 ITEM 中包含了多个 string 类型字段,在 exe 中的 ExeFunc 中定义 ITEM 变量 item,传 item 的引用到 DllFunc 函数中,DllFunc 是一个 dll 的导出函数,负责从文件中读取一些数据到 ITEM 结构中。在 ExeFunc 结束的时候 string 异常了,提示堆内存损坏。排除法发现多个 string 字段中只有一个引发了异常,其它的都没有问题,觉得很奇怪。string 异常的字段赋值的字符串大于 16 个字符(string 默认是15 还是 16 个 byte 来着)其它的都小于 16 个字符,显然是 string 对象重新分配内存了。

  查看内存也没有发现异常情况,怀疑 string 有问题,于是另外建了个工程测试 string,单个 exe 或者模拟工程中建立一个 dll 赋值给引用 string 变量都正常,而且字符数大于 16 个。

  跟踪定位到 _CrtIsValidHeapPointer ,注意到 dbgheap.c 文件中 _CrtIsValidHeapPointer 处注释:

         /*
         * If this ASSERT fails, a bad pointer has been passed in. It may be
         * totally bogus, or it may have been allocated from another heap.
         * The pointer MUST come from the 'local' heap.
         */

         _ASSERTE(_CrtIsValidHeapPointer(pUserData));

  搜索到一些关于本地堆(local heap)的文章,才明白是因为 dll 如果静态链接了运行时库,dll 就会拥有独立于应用程序堆(也称作local heap)的运行时堆实例。此时在 dll 外部就不能访问此 local heap,所以也就有上面所出现的异常啦。MSDN 中也有介绍:

  The _CrtIsValidHeapPointer function is used to ensure that a specific memory address is within the local heap. The local heap refers to the heap created and managed by a particular instance of the C run-time library. If a dynamic-link library (DLL) contains a static link to the run-time library, it has its own instance of the run-time heap, and therefore its own heap, independent of the application's local heap. When _DEBUG is not defined, calls to _CrtIsValidHeapPointer are removed during preprocessing.

  查找这个问题浪费了不少的时间,解决办法就是在编译 dll 时动态链接运行时库( VS2005 下动态链接 MFC 库默认就是动态链接运行时库,如果更改静态链接 MFC 库,运行时库的链接方式也跟着改变为静态的),并且 exe 中也要使用相同的链接方式才行。这或许是有时候改变 MFC 库的链接方式会引起一些莫名错误的原因吧;对了在 _CrtIsValidHeapPointer 内部也有这样的注释:

         /*
         * Go through the heap regions and see if the pointer lies within one
         * of the regions of the local heap.
         *
         * Pointers from non-local heaps cannot be handled. For example, a
         * non-local pointer may come from a DLL that has the CRT linked-in.
         *
         */

  结论:应用程序使用的 dll 库在链接时尽量使用相同的链接方式,大多数情况下不同的链接方式不会出现问题,但有少数情况总是存在的。额要是在第一时间看清楚明了的 MSDN 就不会走N多的弯路了:(

 

 

原文出处:http://hi.baidu.com/anowsober/blog/item/9c1abcd95d20b4ee38012f6b.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值