Summary of Memory Allocation Rules

The following table summarizes key rules regarding memory allocation:

MIDL element Description
Top-level ref pointers Must be non-null pointers.
Function return value New memory is always allocated for pointer return values.
unique, out or ptr, out pointer Not allowed by MIDL.
Non-top-level unique, in, out or ptr, in, out pointer that changes from null to non-null Client stubs allocate new memory on client on return.
Non-top-level unique, in, out pointer that changes from non-null to null Memory is orphaned on client; client application is responsible for freeing memory and preventing leaks.
Non-top-level ptr, in, out pointer that changes from non-null to null Memory will be orphaned on client if not aliased; client application is responsible for freeing and preventing memory leaks in this case.
ref pointers Client-application layer usually allocates.
Non-null in, out pointer Stubs attempt to write into existing storage on client. If string and size increases beyond size allocated on the client, it will cause a GP-fault on return.

The following table summarizes the effects of key IDL and ACF attributes on memory management:

MIDL feature Client issues Server issues
allocate(single_node), allocate(all_nodes) Determines whether one or many calls are made to the memory functions. Same as client, except private memory can often be used for allocate (single_node) [in] and [in,out] data.
allocate(free) or allocate(dont_free) (None; affects server) Determines whether memory on the server is freed after each remote procedure call.
array attributes max_is and size_is (None; affects server) Determines size of memory to be allocated.
byte_count Client must allocate buffer; not allocated or freed by client stubs. ACF parameter attribute determines size of buffer allocated on server.
enable_allocate Usually, none. However, the client may be using a different memory management environment. Server uses a different memory management environment. RpcSmAllocate should be used for allocations.
in attribute Client application responsible for allocating memory for data. Allocated on server by stubs.
out attribute Allocated on client by stubs. out-only pointer must be ref pointer; allocated on server by stubs.
ref attribute Memory referenced by pointer must be allocated by client application. Top-level and first-level reference pointers managed by stubs.
unique attribute Non-null to null can result in orphaned memory; null to non-null causes client stub to call midl_user_allocate. (Affects client)
ptr attribute (See unique) (See unique)