There are a lot of different memory allocators in the Mozilla source tree. This article looks over some of them and tries to sort out which should be used under what circumstances.
Allocating memory in XPCOM
These are general purpose memory-management routines that you should use unless your code falls into one of the other categories below. Use these if you link against XPCOM or XPCOM Glue; this includes extensions with binary components. See the XPCOM string guide for additional information.
nsMemory::Clone()(note: not part of nsIMemory)
See Infallible memory allocation for information about how to allocate memory infallibly; that is, how to use memory allocators that will only return valid memory buffers, and never return
Allocating strings in XPCOM code
See "Callee-allocated Parameters" in the XPCOM Strings guide; use
ToNewUnicode() to allocate strings that will be passed out. These methods convert
ns*String to nsIMemory allocated, unowned
Do not use
nsCRT::strdup for returning values from an XPCOM object, as that uses a different allocator.
NSPR memory allocators
You should only use the NSPR allocators within NSPR or the security code located in the <tt>/security/</tt> subtree of the source code. Avoid using them elsewhere.
PR_Alloc()(do not use, no users and only exists in <tt>/security/</tt>; use
PR_NEW(pass in a struct to allocate its size)
PR_NEW, but zeros memory)
PR_Free()and also clears the pointer)
PR_vsprintf_append()must be freed with
PL_strndup()must be freed with
nsCRT::strdup/nsCRT::strndupmust be freed with
Allocating memory within plugins
There are special memory allocation routines specifically intended for use from plugins, which must not be used from within Mozilla itself. See Gecko Plugin API Reference:Memory.
NSPR exposes arena allocators that can be used to efficiently allocate lots of small, uniformly sized objects.
nsPresContext::AllocateFromShell() can be used to allocate memory from an arena maintained by the PresShell. These should only be used to allocate objects that are guaranteed to have a shorter lifetime than the PresShell in question (typically layout data structures), because the PresShell destructor will wipe out the arena, leaving any pointers to memory allocated from it dangling.
The corresponding deallocators are
Because C++ objects that implement XPCOM interface types delete themselves when the final
Release() is called, they can be safely allocated using the native
delete operators. The
NS_DELETEXPCOM macro wrappers are entirely unnecessary and make code harder to read.
Memory that is allocated with the C standard library (
free()) should not be passed between shared libraries. These memory buffers may be used within a single shared library or program. For data structures being passed across XPCOM boundaries, use