跨模块传参数的教训


VC开发环境下C运行库有6个版本
DEBUG 单线程、多线程、多线程DLL
RELEASE 单线程、多线程、多线程DLL


不同模块分配的内存可以分配方式不一样,在另一个模块中释放时会导致错误。
其中单线程和多线程的内存管理模式不一样.


比如EXE调用DLL,DLL返加CString对象,这个对象的构造通过函数返回出栈的过程中,DLL中分配的内存,到EXE中析构就会报错。

每一个静态链接的CRT都会有一个默认堆吧,在EXE中NEW一个指针传递到DLL里去delete会产生堆破坏,是不是因为new在一个堆上,而delete在另一个堆上.

windows via  c/c++ 关于DLL的讲述里面似乎有内容.
windows核心编程上有提到这个问题

谁申请,谁删除.


进程初始化时会有一个默认堆,如果EXE和DLL都静态链接CRT,那这时是不是有3个堆

对于静态CRT链接,EXE或者DLL中的NEW,DELETE都是在CRT各自创建的堆中去操作,所以不能跨模块释放,如果用GlobalAlloc代替NEW则不会,
这时因为GlobalAlloc实在进程的默认堆上分配的,是这样么.



这是在项目中碰到的。
下面是代码:
//de.cpp
#include <string>
#include 
<iostream>
using namespace  std;
extern "C" void getString(string &
str);

int main(int argc,char **
argv)
{
    
string
 str;
    getString(str);
    cout 
<<
 str;
    
return 0
;
}

//dll.cpp
#include <string>
#include 
<iostream>
using namespace  std;
extern "C" void getString(string &
str)
{
    
int
 i;
    
str += "string modified.mybe cause a exception." ;
}

将dll.cpp连接成dll形式,运行de.exe有时候很正常,但有时候会发现有异常出现,异常是delete释放了一个非法的指针。这取决于连接的运行库是动态的还是静态的,他会在静态连接时出问题。
产生这个问题的原因是因为std::string类的内存分配器分配了内存,而在de.cpp里释放,两个模块分别有自己的运行堆,分配和释放没有在同一个堆里进行。
原因很简单,但是有时后就会忽略,尤其在模块很多和频繁使用stl容器的时候,当从别人那里得到一个模块接口时,如果有一个需要stl容器引用的接口时就要注意运行库的问题。
posted on 2005-11-24 10:24 psysun 阅读(845) 评论(6)   编辑  收藏 引用

评论:
#  re: 在跨模块调用中传递stl容器的问题。2005-11-24 13:41 | 小明
link 的时候使用C++ Multi Thread Dll 库,就应该没问题   回复   更多评论
  
#  re: 在跨模块调用中传递stl容器的问题。2005-11-24 17:39 | psysun
和多线程库没关系,是连接方式的问题。
总的原则是:在跨模块的接口里如果有用非常量stl容器引用作为参数的函数,那么就要保证这两个模块都用动态连接运行库方式连接的。用指针传递参数时分配和释放不再同一模块也有同样的问题。   回复   更多评论
  
#  re: 在跨模块调用中传递stl容器的问题。2005-11-28 13:52 | hotjock
是不是用动态方式链接就能保证调用模块和被调用模块公用一个堆?还有就是STL如何释放或者讲何时释放由被调用模块重新new出来的空间(就象上面例子中的那样),采用动态链接就一定可以避免吗?   回复   更多评论
  
#  re: 在跨模块调用中传递stl容器的问题。2005-11-28 19:23 | psysun
和动态链接没关系,重要的是共享运行时库。
因为stl容器都是以头文件形式定义的,所以每个模块编译后都至少有一份stl代码,在上面的例子里operator+=就是在dll.obj模块里,而~string()代码在de.obj,他们都使用了allocator<>,这个模版最后会用malloc和free管理内存,这时如果有一个模块静态链接了运行库,那么堆就不是唯一的,就会出异常了。
stl容器在分配内存时会根据算法用malloc分配一个比需要更大的内存,free掉原来的内存,用new(p) value_type(x)构造新对象,调用的是拷贝构造函数,用p->~value_type()析构对象。   回复   更多评论
  
#  re: 在跨模块调用中传递stl容器的问题。2005-11-29 17:21 | hotjock
如同你最初给出的那个例子,怎样做就可以保证不出异常。

一个新手,希望讲的详细些。   回复   更多评论
  
#  re: 在跨模块调用中传递stl容器的问题。 2005-12-11 23:30 | psysun
再连接时用动态方式链接运行库就能避免了。vc里就是/MD





跨模块传参数的教训
今天遇到一个比较奇怪的crash问题,这里记录下。这个crash是由QA设置了一些不合理的参数引起的,还好QA当时保存了Dump文件,让我们可以慢慢分析,从而找出代码中隐藏的问题。
    
这里先简单介绍下ATL/WTL里字符串的设计:
(1)每个CString都有自己的串头(内含引用计数,数据长度,已分配内存长度),紧接着后面是真正的数据。
因为是基于引用计数,所以相同的多个CString可以共享同一份数据。
struct CStringData
{
     long nRefs;      //  reference count
     int nDataLength;
     int nAllocLength;
     //  TCHAR data[nAllocLength]

    TCHAR* data()
    {  return (TCHAR*)( this + 1); }
};


(2)每个未初始化CString都会指向同一固定的全局数据,内部引用计数、数据长度、已分配内存长度、内容分别为-1,0,0,0
//  Globals

//  For an empty string, m_pchData will point here
//  (note: avoids special case of checking for NULL m_pchData)
//  empty string data (and locked)
_declspec(selectany)  int rgInitData[] = { -1, 0, 0, 0 };
_declspec(selectany) CStringData* _atltmpDataNil = (CStringData*)&rgInitData;
_declspec(selectany) LPCTSTR _atltmpPchNil = (LPCTSTR)(((BYTE*)&rgInitData) +  sizeof(CStringData));

inline CString::CString()
{
Init();
}
inline void CString::Init()
{ m_pchData = _GetEmptyString().m_pchData; }

static const CString& __stdcall _GetEmptyString()
{
return *(CString*)&_atltmpPchNil;
}

(3)字符串析构时会检测是否已经分配内存,是否其他没有人用(引用计数小于0),都满足后才会最终释放内存。
inline CString::~CString()
//   free any attached data
{
     if (GetData() != _atltmpDataNil)
    {
         if (InterlockedDecrement(&GetData()->nRefs) <= 0)
              delete[] (BYTE * )GetData();
    }
}

 用Windbg打开Dump文件,输入!analyze -v 让它自动分析Crash时的情况,最终发现Crash在ATL/WTL字符串的析构函数 ~CString()里的delete语句, 然后我们通过分析传入参数,发现外部传入的是一个没有初始化的CString,既然是没有初始化的CString,那应该都是指向初始字符串的固定内存,也就不会满足条件  if  (GetData() != _atltmpDataNil),为什么会跑到里面去呢?

这里关键原因就是这个CString是跨模块传递过来的,比如你DLL里有个导出函数void SetValue(CString strValue), 然后你外部Exe传递一个未出始化的字符串CString str; SetValue(str); 这时就会Crash。根本原因是因为传入的字符串是在Exe里构造,但是在DLL里析构,Exe里的未初始化str指向的是Exe模块自己的全局初始值Exe! _atltmpDataNil, 而DLL内CString的全局初始值是Dll自己的Dll!_atltmpDataNil, 两者比较当然不相等,而后面的 if  (InterlockedDecrement(&GetData()->nRefs) <= 0)又会把引用计数从-1改成-2, 接下来就会试图delete这块不是new出来的全局内存,当然会Crash了。

这个Bug一直没有发现的原因是QA一直设置的都是有效参数,也就不会引起传入未初始化的CString的情况,但这次意外却暴露了我们代码中隐藏的问题。

知道了原因,接下来就是如何改了?方法很多,可以用传引用的方式CString&;也可以传C方式的字符串LPCTSTR;也可以还是传CString, 但是在传之前先做下长度判断,以确保已经出始化。

另外提醒下如果要在模块(DLL)之间传递内存,要确保C/C++运行库要用DLL的方式(MD), 这样跨模块new和delete时他们会共享同一个内存堆,不同模块之间相互new和delete才不会有问题。

测试工程: DllStringTest

经典问题了,MD虽然可以解决,但个人感觉,还是应该养成哪里分配哪里释放的好。跨DLL释放总不是很好。。


我觉得还是传char *比较保险,不要传类  

恩,跨模块返回一个未初始化的CString会有同样的问题,
所以跨模块还是用C语言的字符串方式比较保险。
 
// ============================================================================= // FILE: StdString.h // AUTHOR: Joe O'Leary (with outside help noted in comments) // // If you find any bugs in this code, please let me know: // // jmoleary@earthlink.net // http://www.joeo.net/stdstring.htm (a bit outdated) // // The latest version of this code should always be available at the // following link: // // http://www.joeo.net/code/StdString.zip (Dec 6, 2003) // // // REMARKS: // This header file declares the CStdStr template. This template derives // the Standard C++ Library basic_string<> template and add to it the // the following conveniences: // - The full MFC CString set of functions (including implicit cast) // - writing to/reading from COM IStream interfaces // - Functional objects for use in STL algorithms // // From this template, we intstantiate two classes: CStdStringA and // CStdStringW. The name "CStdString" is just a #define of one of these, // based upone the UNICODE macro setting // // This header also declares our own version of the MFC/ATL UNICODE-MBCS // conversion macros. Our version looks exactly like the Microsoft's to // facilitate portability. // // NOTE: // If you you use this in an MFC or ATL build, you should include either // afx.h or atlbase.h first, as appropriate. // // PEOPLE WHO HAVE CONTRIBUTED TO THIS CLASS: // // Several people have helped me iron out problems and othewise improve // this class. OK, this is a long list but in my own defense, this code // has undergone two major rewrites. Many of the improvements became // necessary after I rewrote the code as a template. Others helped me // improve the CString facade. // // Anyway, these people are (in chronological order): // // - Pete the Plumber (???) // - Julian Selman // - Chris (of Melbsys) // - Dave Plummer // - John C Sipos // - Chris Sells // - Nigel Nunn // - Fan Xia // - Matthew Williams // - Carl Engman // - Mark Zeren // - Craig Watson // - Rich Zuris // - Karim Ratib // - Chris Conti // - Baptiste Lepilleur // - Greg Pickles // - Jim Cline // - Jeff Kohn // - Todd Heckel // - Ullrich Poll?hne // - Joe Vitaterna // - Joe Woodbury // - Aaron (no last name) // - Joldakowski (???) // - Scott Hathaway // - Eric Nitzche // - Pablo Presedo // - Farrokh Nejadlotfi // - Jason Mills // - Igor Kholodov // - Mike Crusader // - John James // - Wang Haifeng // - Tim Dowty // - Arnt Witteveen // - Glen Maynard // - Paul DeMarco // - Bagira (full name?) // - Ronny Schulz // - Jakko Van Hunen // - Charles Godwin // - Henk Demper // - Greg Marr // - Bill Carducci // - Brian Groose // - MKingman // - Don Beusee // // REVISION HISTORY // // 2005-JAN-10 - Thanks to Don Beusee for pointing out the danger in mapping // length-checked formatting functions to non-length-checked // CRT equivalents. Also thanks to him for motivating me to // optimize my implementation of Replace() // // 2004-APR-22 - A big, big thank you to "MKingman" (whoever you are) for // finally spotting a silly little error in StdCodeCvt that // has been causing me (and users of CStdString) problems for // years in some relatively rare conversions. I had reversed // two length arguments. // // 2003-NOV-24 - Thanks to a bunch of people for helping me clean up many // compiler warnings (and yes, even a couple of actual compiler // errors). These include Henk Demper for figuring out how // to make the Intellisense work on with CStdString on VC6, // something I was never able to do. Greg Marr pointed out // a compiler warning about an unreferenced symbol and a // problem with my version of Load in MFC builds. Bill // Carducci took a lot of time with me to help me figure out // why some implementations of the Standard C++ Library were // returning error codes for apparently successful conversions // between ASCII and UNICODE. Finally thanks to Brian Groose // for helping me fix compiler signed unsigned warnings in // several functions. // // 2003-JUL-10 - Thanks to Charles Godwin for making me realize my 'FmtArg' // fixes had inadvertently broken the DLL-export code (which is // normally commented out. I had to move it up higher. Also // this helped me catch a bug in ssicoll that would prevent // compilation, otherwise. // // 2003-MAR-14 - Thanks to Jakko Van Hunen for pointing out a copy-and-paste // bug in one of the overloads of FmtArg. // // 2003-MAR-10 - Thanks to Ronny Schulz for (twice!) sending me some changes // to help CStdString build on SGI and for pointing out an // error in placement of my preprocessor macros for ssfmtmsg. // // 2002-NOV-26 - Thanks to Bagira for pointing out that my implementation of // SpanExcluding was not properly handling the case in which // the string did NOT contain any of the given characters // // 2002-OCT-21 - Many thanks to Paul DeMarco who was invaluable in helping me // get this code working with Borland's free compiler as well // as the Dev-C++ compiler (available free at SourceForge). // // 2002-SEP-13 - Thanks to Glen Maynard who helped me get rid of some loud // but harmless warnings that were showing up on g++. Glen // also pointed out that some pre-declarations of FmtArg<> // specializations were unnecessary (and no good on G++) // // 2002-JUN-26 - Thanks to Arnt Witteveen for pointing out that I was using // static_cast<> in a place in which I should have been using // reinterpret_cast<> (the ctor for unsigned char strings). // That's what happens when I don't unit-test properly! // Arnt also noticed that CString was silently correcting the // 'nCount' argument to Left() and Right() where CStdString was // not (and crashing if it was bad). That is also now fixed! // // 2002-FEB-25 - Thanks to Tim Dowty for pointing out (and giving me the fix // for) a conversion problem with non-ASCII MBCS characters. // CStdString is now used in my favorite commercial MP3 player! // // 2001-DEC-06 - Thanks to Wang Haifeng for spotting a problem in one of the // assignment operators (for _bstr_t) that would cause compiler // errors when refcounting protection was turned off. // // 2001-NOV-27 - Remove calls to operator!= which involve reverse_iterators // due to a conflict with the rel_ops operator!=. Thanks to // John James for pointing this out. // // 2001-OCT-29 - Added a minor range checking fix for the Mid function to // make it as forgiving as CString's version is. Thanks to // Igor Kholodov for noticing this. // - Added a specialization of std::swap for CStdString. Thanks // to Mike Crusader for suggesting this! It's commented out // because you're not supposed to inject your own code into the // 'std' namespace. But if you don't care about that, it's // there if you want it // - Thanks to Jason Mills for catching a case where CString was // more forgiving in the Delete() function than I was. // // 2001-JUN-06 - I was violating the Standard name lookup rules stated // in [14.6.2(3)]. None of the compilers I've tried so // far apparently caught this but HP-UX aCC 3.30 did. The // fix was to add 'this->' prefixes in many places. // Thanks to Farrokh Nejadlotfi for this! // // 2001-APR-27 - StreamLoad was calculating the number of BYTES in one // case, not characters. Thanks to Pablo Presedo for this. // // 2001-FEB-23 - Replace() had a bug which caused infinite loops if the // source string was empty. Fixed thanks to Eric Nitzsche. // // 2001-FEB-23 - Scott Hathaway was a huge help in providing me with the // ability to build CStdString on Sun Unix systems. He // sent me detailed build reports about what works and what // does not. If CStdString compiles on your Unix box, you // can thank Scott for it. // // 2000-DEC-29 - Joldakowski noticed one overload of Insert failed to do a // range check as CString's does. Now fixed -- thanks! // // 2000-NOV-07 - Aaron pointed out that I was calling static member // functions of char_traits via a temporary. This was not // technically wrong, but it was unnecessary and caused // problems for poor old buggy VC5. Thanks Aaron! // // 2000-JUL-11 - Joe Woodbury noted that the CString::Find docs don't match // what the CString::Find code really ends up doing. I was // trying to match the docs. Now I match the CString code // - Joe also caught me truncating strings for GetBuffer() calls // when the supplied length was less than the current length. // // 2000-MAY-25 - Better support for STLPORT's Standard library distribution // - Got rid of the NSP macro - it interfered with Koenig lookup // - Thanks to Joe Woodbury for catching a TrimLeft() bug that // I introduced in January. Empty strings were not getting // trimmed // // 2000-APR-17 - Thanks to Joe Vitaterna for pointing out that ReverseFind // is supposed to be a const function. // // 2000-MAR-07 - Thanks to Ullrich Poll?hne for catching a range bug in one // of the overloads of assign. // // 2000-FEB-01 - You can now use CStdString on the Mac with CodeWarrior! // Thanks to Todd Heckel for helping out with this. // // 2000-JAN-23 - Thanks to Jim Cline for pointing out how I could make the // Trim() function more efficient. // - Thanks to Jeff Kohn for prompting me to find and fix a typo // in one of the addition operators that takes _bstr_t. // - Got rid of the .CPP file - you only need StdString.h now! // // 1999-DEC-22 - Thanks to Greg Pickles for helping me identify a problem // with my implementation of CStdString::FormatV in which // resulting string might not be properly NULL terminated. // // 1999-DEC-06 - Chris Conti pointed yet another basic_string<> assignment // bug that MS has not fixed. CStdString did nothing to fix // it either but it does now! The bug was: create a string // longer than 31 characters, get a pointer to it (via c_str()) // and then assign that pointer to the original string object. // The resulting string would be empty. Not with CStdString! // // 1999-OCT-06 - BufferSet was erasing the string even when it was merely // supposed to shrink it. Fixed. Thanks to Chris Conti. // - Some of the Q172398 fixes were not checking for assignment- // to-self. Fixed. Thanks to Baptiste Lepilleur. // // 1999-AUG-20 - Improved Load() function to be more efficient by using // SizeOfResource(). Thanks to Rich Zuris for this. // - Corrected resource ID constructor, again thanks to Rich. // - Fixed a bug that occurred with UNICODE characters above // the first 255 ANSI ones. Thanks to Craig Watson. // - Added missing overloads of TrimLeft() and TrimRight(). // Thanks to Karim Ratib for pointing them out // // 1999-JUL-21 - Made all calls to GetBuf() with no args check length first. // // 1999-JUL-10 - Improved MFC/ATL independence of conversion macros // - Added SS_NO_REFCOUNT macro to allow you to disable any // reference-counting your basic_string<> impl. may do. // - Improved ReleaseBuffer() to be as forgiving as CString. // Thanks for Fan Xia for helping me find this and to // Matthew Williams for pointing it out directly. // // 1999-JUL-06 - Thanks to Nigel Nunn for catching a very sneaky bug in // ToLower/ToUpper. They should call GetBuf() instead of // data() in order to ensure the changed string buffer is not // reference-counted (in those implementations that refcount). // // 1999-JUL-01 - Added a true CString facade. Now you can use CStdString as // a drop-in replacement for CString. If you find this useful, // you can thank Chris Sells for finally convincing me to give // in and implement it. // - Changed operators << and >> (for MFC CArchive) to serialize // EXACTLY as CString's do. So now you can send a CString out // to a CArchive and later read it in as a CStdString. I have // no idea why you would want to do this but you can. // // 1999-JUN-21 - Changed the CStdString class into the CStdStr template. // - Fixed FormatV() to correctly decrement the loop counter. // This was harmless bug but a bug nevertheless. Thanks to // Chris (of Melbsys) for pointing it out // - Changed Format() to try a normal stack-based array before // using to _alloca(). // - Updated the text conversion macros to properly use code // pages and to fit in better in MFC/ATL builds. In other // words, I copied Microsoft's conversion stuff again. // - Added equivalents of CString::GetBuffer, GetBufferSetLength // - new sscpy() replacement of CStdString::CopyString() // - a Trim() function that combines TrimRight() and TrimLeft(). // // 1999-MAR-13 - Corrected the "NotSpace" functional object to use _istpace() // instead of _isspace() Thanks to Dave Plummer for this. // // 1999-FEB-26 - Removed errant line (left over from testing) that #defined // _MFC_VER. Thanks to John C Sipos for noticing this. // // 1999-FEB-03 - Fixed a bug in a rarely-used overload of operator+() that // caused infinite recursion and stack overflow // - Added member functions to simplify the process of // persisting CStdStrings to/from DCOM IStream interfaces // - Added functional objects (e.g. StdStringLessNoCase) that // allow CStdStrings to be used as keys STL map objects with // case-insensitive comparison // - Added array indexing operators (i.e. operator[]). I // originally assumed that these were unnecessary and would be // inherited from basic_string. However, without them, Visual // C++ complains about ambiguous overloads when you try to use // them. Thanks to Julian Selman to pointing this out. // // 1998-FEB-?? - Added overloads of assign() function to completely account // for Q172398 bug. Thanks to "Pete the Plumber" for this // // 1998-FEB-?? - Initial submission // // COPYRIGHT: // 2002 Joseph M. O'Leary. This code is 100% free. Use it anywhere you // want. Rewrite it, restructure it, whatever. If you can write software // that makes money off of it, good for you. I kinda like capitalism. // Please don't blame me if it causes your $30 billion dollar satellite // explode in orbit. If you redistribute it in any form, I'd appreciate it // if you would leave this notice here. // ============
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值