# 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 &emdash; including the return value &emdash; that are not passed by value:

- in parameters must be allocated and freed by the caller.

- out parameter must be allocated by the one called; freed by the caller using the standard COM task memory allocator. Refer to The OLE Memory Allocator for more information.

- in-out parameter is initially allocated by the caller, then freed and re-allocated by the one called, if necessary. As is true for out parameters, the caller is responsible for freeing the final returned value. The standard COM memory allocator must be used.

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 &emdash; there is no requirement at all that memory allocation strictly internal to a COM application need be done using these mechanisms.