Memory Management Rules

The life-time of pointers to interfaces is always managed through the AddRef and Release methods on every COM interface. For more information, refer to Rules for Managing Reference Counts.

For all other parameters, it is important to adhere to certain rules for managing memory. The following rules apply to all parameters of interface methods — including the return value — that are not passed by value:

In the latter two cases, where one piece of code allocates the memory and a different piece of code frees it, using the COM allocator ensures that the two pieces of code are using the same allocation methods.

Another area that needs special attention is the treatment of out and in-out parameters in failure conditions. If a function returns a a failure code, the caller typically has no way to clean up the out or in-out parameters. This leads to a few additional rules:

Parameters must always be reliably set to a value that will be cleaned up without any action by the caller, in case of an error condition.

All out pointer parameters must explicitly be set to NULL. These are usually passed in a pointer-to-pointer parameter, but can also be passed as a member of a structure that the caller allocates and the called code fills. The most straightforward way to ensure this is (in part) to set these values to NULL on function entry. This rule is important, because it promotes more robust application interoperability.

Under error conditions, all in-out parameters must either be left alone by the code called (thus remaining at the value to which they were initialized by the caller) or be explicitly set, as in the out-parameter error return case.

Remember that these memory management conventions for COM applications apply only across public interfaces and APIs — there is no requirement at all that memory allocation strictly internal to a COM application need be done using these mechanisms.