posts - 0,  comments - 2,  trackbacks - 0
http://www.davidlenihan.com/2008/01/choosing_the_correct_cc_runtim.html 
Choosing the Correct C/C++ Runtime Library

DLL and Application Address space

It is important to realize that a single address space consists of one executable module and several DLL modules. Some of these modules can link to a static version of the C/ C++ run-time library, some of these modules might link to a DLL version of the C/C++ run-time library, and some of these modules (if not written in C/C++) might not require the C/ C++ run-time library at all. Many developers make a common mistake because they forget that several C/C++ run-time libraries can be present in a single address space. Examine the following code:

VOID EXEFunc() {
PVOID pv = DLLFunc();
// Access the storage pointed to by pv...
// Assumes that pv is in EXE's C/C++ run-time heap
free(pv);
}
PVOID DLLFunc() {
// Allocate block from DLL's C/C++ run-time heap
return(malloc(100));
}

So, what do you think? Does the preceding code work correctly? Is the block allocated by the DLL's function freed by the EXE's function? The answer is: maybe. The code shown does not give you enough information. If both the EXE and the DLL link to the DLL C/C++ run-time library, the code works just fine. However, if one or both of the modules link to the static C/C++ run-time library, the call to free fails. I have seen developers write code similar to this too many times, and it has burned them all.

There is an easy fix for this problem. When a module offers a function that allocates memory, the module must also offer a function that frees memory. Let me rewrite the code just shown:

VOID EXEFunc() {
PVOID pv = DLLFunc();
// Access the storage pointed to by pv...
// Makes no assumptions about C/C++ run-time heap
DLLFreeFunc(pv);
}
PVOID DLLFunc() {
// Allocate block from DLL's C/C++ run-time heap
PVOID pv = malloc(100);
return(pv);
}
BOOL DLLFreeFunc(PVOID pv) {
// Free block from DLL's C/C++ run-time heap
return(free(pv));
}

This code is correct and will always work. When you write a module, don't forget that functions in other modules might not even be written in C/C++ and therefore might not use malloc and free for memory allocations. Be careful not to make these assumptions in your code. By the way, this same argument holds true for the C++ new and delete operators while calling malloc and free internally.

posted on 2008-10-28 09:50 Sean 阅读(179) 评论(0)  编辑 收藏 引用
只有注册用户登录后才能发表评论。
<2024年5月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

hello! 欢迎常来我这里逛逛!

常用链接

留言簿(2)

文章分类(3)

文章档案(4)

相册

收藏夹(4)

搜索

  •  

最新评论