Reputation: 1115
Why is it that the MS Security examples seem to use one memory allocation routine in the documentation for one function, and another one in a different one?
I have found an example where they actually use different ones at different points in the example code. See the GetAppContainerNamedObjectPath
function.
This uses both HeapAlloc
when allocating a SID and LocalAlloc
when allocating a security descriptor. Both allocations are freed before the example ends, why are they using different methods? I've seen people use ::malloc
in blog examples.
Upvotes: 2
Views: 425
Reputation: 1269
MS Security examples do not use malloc as according to me the malloc function has the disadvantage of being run-time dependency, HeapAlloc(which uses RtlReAllocateHeap) won't allocate memory for 0 sized pointers, where malloc would plus LocalAlloc have greater overhead than HeapAlloc, but less than malloc.
Upvotes: 0
Reputation: 54600
LocalAlloc
and HeapAlloc
are the same in this case. This was not always the case, but it has been for a decade at least. I know, it's confusing, but it's all the result of legacy 16bit systems and backwards compatibility. See this documentation:
Windows memory management does not provide a separate local heap and global heap, as 16-bit > Windows does. As a result, the global and local families of functions are equivalent and choosing between them is a matter of personal preference.
See also this documentation:
There is no difference between memory allocated from a private heap and that allocated by using the other memory allocation functions. For a complete list of functions, see the table in Memory Management Functions.
There are differences, so always read the documentation for the memory function. For example, CoTaskMemFree
handles NULL but HeapFree
does not. The different allocation functions will give you different degrees of control over how the memory is allocated and shared among OS objects (processes, etc). But if you just want some plain old memory for your process, always check the documentation for the API you are using, as it may specify that you should use specific allocation or freeing functions, but otherwise, just pick one and be consistent.
As for why the documentation switches it up? My guess is it was hacked on by more than one person over time, none of which were actual OS team members. MSDN sample code is notoriously bad. There should be a way for you to flag it or leave feedback on the MSDN page.
Upvotes: 1