Re: Exported class's object deletion problem
Faisal wrote:
I've two projects. One is regular dll and another is a MFC dialog
based application.
In the dll I've exported one class CFoo.
#ifdef TSTDLL_EXPORTS
#define TST_API __declspec(dllexport)
#else
#define TST_API __declspec(dllimport)
#endif
class TST_API CFoo
{
public:
string str;
};
From the MFC application I created an object of CFoo and set the
public member str(of type std::string). In the debug build, While
delete this object application crashes.
void CUITestDlg::OnBtnStop()
{
CFoo* pFoo = new CFoo;
pFoo->str = _T("hello");
delete pFoo; //application crashes here in the debug build
}
1. If 'string' actually means 'std::string', assignment of _T("hello") is
wrong. _T() is for TCHAR literals, but std::string is based on char. If you
want to use TCHAR, use std::basic_string<TCHAR>. The point is that this
already could break your program if the meaning of TCHAR changes. This can
easily change since TCHAR depends on _UNICODE/UNICODE and your DLL doesn't
control whether the application uses those. It could create an #error if
those are not what it expects or it could compile into two versions, one
using TCHAR=char and the other TCHAR=wchar_t.
2. Similarly to the two TCHAR-versions, you will also need one debug and
release version. Note that you should link both to the DLL runtime, not the
static runtime, so that you don't free memory to one heap that is allocated
from a different one.
_CrtIsValidHeapPointer(const void * 0x00b01050) line 1606
If this fails, it could be that exactly that was wrong.
BTW: take a look at "#pragma comment(lib, ..)". Using that and looking at
_UNICODE/UNICODE and NDEBUG/_DEBUG, you can automatically select the
correct DLL to use at compile-time. This is the way that e.g. the MFC
works, with an optional 'u' and 'd' suffix.
By analysing I understand that the creation and deletion of object
from a different Exe/Dll causing the problem.
[...]
1. Is it necessary that creation and deletion code of an exported
class's object should be with in the dll?
No, but you have to assure some consistency. Always use a dynamic runtime
and assure to never mix debug and release versions.
2. If not why there is heap corruption with deletion?
That's just because you are using different runtimes and thus different
heaps or since the types just don't match due to TCHAR inconsistencies.
3. Is it problem specific to stl's std::string?
No. BTW: the STL is dead, though large parts of it live on in the C++
standard library.
Uli
--
C++ FAQ: http://parashift.com/c++-faq-lite
Sator Laser GmbH
Gesch??ftsf??hrer: Thorsten F??cking, Amtsgericht Hamburg HR B62 932