|Date:||September 15, 2006 / year-entry #314|
|Summary:||I'm sure it's been drilled into your head by now that you have to free memory with the same allocator that allocated it. LocalAlloc matches LocalFree, GlobalAlloc matches GlobalFree, new matches delete. But this rule goes deeper. If you have a function that allocates and returns some data, the caller must know how to free...|
I'm sure it's been drilled into your head by now that you have to free memory with the same allocator that allocated it.
If you have a function that allocates and returns some data, the caller must know how to free that memory. You have a variety of ways of accomplishing this. One is to state explicitly how the memory should be freed. For example, the
Note, however, that if you decide that a block of memory should be freed with the C runtime, such as with
If you choose to link with the static runtime library, then your module has its own private copy of the C/C++ runtime. When your module calls
If you're paying close attention, you might spot a looming problem. Requiring all your clients to use a particular version of the C/C++ runtime might seem reasonable if you control all of the clients and are willing to recompile all of them each time the compiler changes. But in real life, people often don't want to take that risk. "If it ain't broke, don't fix it." Switching to a new compiler risks exposing a subtle bug, say, forgetting to declare a variable as volatile or inadvertently relying on temporaries having a particular lifetime.
In practice, you may wish to convert only part of your program to a new compiler while leaving old modules alone. (For example, you may want to take advantage of new language features such as templates, which are available only in the new compiler.) But if you do that, then you lose the ability to free memory that was allocated by the old DLL, since that DLL expects you to use
The solution to this requires planning ahead. One option is to use a fixed external allocator such as
Another option is to wrap your preferred allocator inside exported functions that manage the allocation. This is the mechanism used by the
Although I personally prefer using a fixed external allocator, many people find it more convenient to use the wrapper technique. That way, they can use their favorite allocator throughout their module. Either way works. The point is that when memory leaves your DLL, the code you gave the memory to must know how to free it, even if it's using a different compiler from the one that was used to build your DLL.
<-- Back to Old New Thing Archive Index