(This article is first published on csdn and is now posted to the blog Park, with slight modifications)
In dynamic connection library development, pay special attention to the issue of memory allocation and release. If you do not pay attention to it, it is very likely to cause memory leakage and thus access errors. For example, a dll contains Code :
Extent "C" _ declspec (dllexport)
Void extractfilename (const STD: string & Path //! <Input path and filename.
, STD: string & fname //! <Extracted filename with extension.
)
{
STD: String: size_type startpos = path. find_last_of ('\\');
Fname. Assign (path. Begin () + startpos + 1, path. End ());
}
Use the STL object STD: string in the DLL and change the content of STD: String in it, that is, the memory redistribution problem occurs, if this function is called in EXE, memory access problems may occur. Mainly because the DLL and exe memory allocation methods are different, the allocated memory in the DLL cannot be correctly released in the exe.
The solution is as follows:
Under normal circumstances: To build a DLL, you must follow the principle of who allocates the DLL and who releases it. For example, the com solution (using reference count) and the object creation (QueryInterface) and released within the COM component. In a pure C ++ environment, similar solutions can be easily implemented.
In the case of applying STL, it is difficult to use the above solution to solve the problem. Therefore, there are two ways to solve this problem:
1. Write your own memory distributor to replace the default one in STL.
2. Use stlport to replace the standard library of the system.
In fact, the above problems have been solved in vc7 and later versions. Note that multi-threaded DLL libraries must be used for DLL projects and called projects so that memory access will not occur.
Two days ago, I saw Jiang Sheng. netArticleThe differences between Visual C ++ 2005 and Visual C ++ 2005 do not support single-threaded CRT (libc. Lib). It seems that this problem will always go to the grave!