September 7th, 2006

You have to free memory with the same allocator that allocated it: Logical consequences

Everybody should know by now that you have to free memory using the same allocator that you used to allocate the memory. If you allocate with new[] then you have to free with delete[]; if you allocate with LocalAlloc then you have to free with LocalFree. Once you’ve internalized this rule, you can use it to draw other logical conclusions. Consider:

When I call the PropertySheet function, who is responsible for freeing the memory that was allocated for the phpage field of the PROPSHEETHEADER structure?

Well, there are two candidates for this responsibility, either the PropertySheet function or the caller of the PropertySheet function. If the PropertySheet function was responsible for freeing the memory, it would have to make sure to use the same allocator that was used to allocate the phpage. But there is no requirement that that memory use any particular allocator. (In fact, a significant portion of the time, the memory is allocated from the stack, in which case there is no explicit deallocation step.) The PropertySheet function would now be required to be psychic and somehow “know” how the memory should be freed (or whether it should be freed at all). Since psychic powers have yet to be perfected in software, this pretty much closes off this line of reasoning.

The only remaining candidate is the caller of the PropertySheet function. Since that’s the code that allocated the memory, it’s the one who knows how to free it.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.