MALLOC(3) BSD Programmer's Manual MALLOC(3)
malloc, calloc, realloc, free, reallocarray, recallocarray, freezero, cfree - memory allocation and deallocation
#include <stdlib.h> void * malloc(size_t size); void * calloc(size_t nmemb, size_t size); void * realloc(void *ptr, size_t size); void free(void *ptr); void * reallocarray(void *ptr, size_t nmemb, size_t size); void * recallocarray(void *ptr, size_t oldnmemb, size_t nmemb, size_t size); void freezero(void *ptr, size_t size); void cfree(void *ptr); char *malloc_options;
Note: if using brk(2) malloc or mmap(2) malloc instead of omalloc, this manual page is inaccurate, especially regarding the protection functions. The malloc() function allocates uninitialised space for an object of the specified size. malloc() maintains multiple lists of free blocks accord- ing to size, allocating space from the appropriate list. The allocated space is suitably aligned (after possible pointer coercion) for storage of any type of object. If the space is of pagesize or larger, the memory returned will be page-aligned. The calloc() function allocates space for an array of nmemb objects, each of the specified size. The space is initialised to zero. The realloc() function changes the size of the object pointed to by ptr to size bytes and returns a pointer to the (possibly moved) object. The contents of the object are unchanged up to the lesser of the new and old sizes. If the new size is larger, the value of the newly allocated por- tion of the object is indeterminate and uninitialised. If the space can- not be allocated, the object pointed to by ptr is unchanged. If ptr is NULL, realloc() behaves like malloc() and allocates a new object. Designed for safe allocation of arrays, the reallocarray() function is similar to realloc() except it operates on nmemb members of size size and checks for integer overflow in the calculation nmemb * size. Used for the allocation of memory holding sensitive data, the recallocar- ray() and freezero() functions guarantee that memory becoming unallocated is explicitly discarded, meaning pages of memory are disposed via munmap(2) and cached free objects are cleared with explicit_bzero(3). The recallocarray() function is similar to reallocarray() except it en- sures newly allocated memory is cleared similar to calloc(). If ptr is NULL, oldnmemb is ignored and the call is equivalent to calloc(). If ptr is not NULL, oldnmemb must be a value such that oldnmemb * size is the size of the earlier allocation that returned ptr, otherwise the behavior is undefined. The freezero() function is similar to the free() function except it en- sures memory is explicitly discarded. If ptr is NULL, no action occurs. If ptr is not NULL, the size argument must be equal to or smaller than the size of the earlier allocation that returned ptr. freezero() guaran- tees the memory range starting at ptr with length size is discarded while deallocating the whole object originally allocated. The free() function causes the space pointed to by ptr to be either placed on a list of free pages to make it available for future allocation or, if required, to be returned to the kernel using munmap(2). If ptr is a NULL pointer, no action occurs. If ptr was previously freed by free(), realloc() or reallocarray(), the behavior is undefined, and the double free is a security concern. A cfree() function is also provided for compatibility with old systems and other malloc libraries; it is simply an alias for free().
Upon successful completion, the functions malloc(), calloc(), realloc() and reallocarray() return a pointer to the allocated space; otherwise, a NULL pointer is returned and errno is set to ENOMEM. If size or nmemb is equal to 0, a unique pointer to an access protected, zero sized object is returned. Access via this pointer will generate a SIGSEGV exception. If multiplying nmemb and size results in integer overflow, calloc(), reallocarray() and recallocarray() return NULL and set errno to ENOMEM. If ptr is not NULL and multiplying oldnmemb and size results in integer overflow recallocarray() returns NULL and sets errno to EINVAL. The free() and cfree() functions return no value.
Consider calloc() or the extensions reallocarray() and recallocarray() when there is multiplication in the size argument of malloc() or real- loc(). For example, avoid this common idiom as it may lead to integer overflow: if ((p = malloc(num * size)) == NULL) err(1, "malloc"); A drop-in replacement is the OpenBSD extension reallocarray(): if ((p = reallocarray(NULL, num, size)) == NULL) err(1, "reallocarray"); Alternatively, calloc() may be used at the cost of possible initialisa- tion overhead. When using realloc(), be careful to avoid the following idiom: size += 50; if ((p = realloc(p, size)) == NULL) return (NULL); Do not adjust the variable describing how much memory has been allocated until the allocation has been successful. This can cause aberrant program behavior if the incorrect size value is used. In most cases, the above sample will also result in a leak of memory. As stated earlier, a return value of NULL indicates that the old object still remains allocated. Better code looks like this: newsize = size + 50; if ((newp = realloc(p, newsize)) == NULL) { free(p); p = NULL; size = 0; return (NULL); } p = newp; size = newsize; As with malloc(), it is important to ensure the new size value will not overflow; i.e. avoid allocations like the following: if ((newp = realloc(p, num * size)) == NULL) { ... Instead, use reallocarray(): if ((newp = reallocarray(p, num, size)) == NULL) { ... Calling realloc() with a NULL ptr is equivalent to calling malloc(). In- stead of this idiom: if (p == NULL) newp = malloc(newsize); else newp = realloc(p, newsize); Use the following: newp = realloc(p, newsize); The recallocarray() function should be used for resizing objects contain- ing sensitive data like keys. To avoid leaking information, it guarantees memory is cleared before placing it on the internal free list. Dealloca- tion of such an object should be done by calling freezero().
MALLOC_OPTIONS See below.
/etc/malloc.conf symbolic link to filename containing option flags
If malloc() must be used with multiplication, be sure to test for over- flow: size_t num, size; ... /* Check for size_t overflow */ if (size && num > SIZE_MAX / size) errc(1, EOVERFLOW, "overflow"); if ((p = malloc(size * num)) == NULL) err(1, "malloc"); The above test is not sufficient in all cases. For example, multiplying signed integers requires a different set of checks: int num, size; ... /* Avoid invalid requests */ if (size < 0 || num < 0) errc(1, EOVERFLOW, "overflow"); /* Check for signed int overflow */ if (size && num > INT_MAX / size) errc(1, EOVERFLOW, "overflow"); if ((p = malloc(size * num)) == NULL) err(1, "malloc"); Assuming the implementation checks for integer overflow as OpenBSD does, it is much easier to use calloc(), reallocarray(), or recallocarray(). The above examples could be simplified to: if ((p = reallocarray(NULL, num, size)) == NULL) err(1, "reallocarray"); or, at the cost of possible initialisation: if ((p = calloc(num, size)) == NULL) err(1, "calloc");
If malloc(), calloc(), realloc(), reallocarray() or free() detect an er- ror condition, a message will be printed to file descriptor 2 (not using stdio). Errors will result in the process being aborted, unless the a op- tion has been specified. Here is a brief description of the error messages and what they mean: "out of memory" If the X option is specified it is an error for malloc(), cal- loc(), realloc() or reallocarray() to return NULL. "malloc init mmap failed" This is a rather weird condition that is most likely to indicate a seriously overloaded system or a ulimit restriction. "bogus pointer (double free?)" An attempt to free(), realloc() or reallocarray() an unallocated pointer was made. "chunk is already free" There was an attempt to free a chunk that had already been freed. "modified chunk-pointer" The pointer passed to free(), realloc() or reallocarray() has been modified. "recursive call" An attempt was made to call recursively into these functions, i.e., from a signal handler. This behavior is not supported. In particular, signal handlers should not use any of the malloc() functions nor utilise any other functions which may call malloc() (e.g., stdio(3) routines). "unknown char in MALLOC_OPTIONS" We found something we didn't understand. "malloc cache overflow/underflow" The internal malloc page cache has been corrupted. "malloc free slot lost" The internal malloc page cache has been corrupted. "guard size" An inconsistent guard size was detected. any other error malloc() detected an internal error; consult sources and/or wizards.
Malloc will first look for a symbolic link called /etc/malloc.conf and next check the environment for a variable called MALLOC_OPTIONS and fi- nally for the global variable malloc_options and scan them for flags in that order. Flags are single letters, uppercase means on, lowercase means off. A "Abort". malloc() will coredump the process, rather than tolerate internal inconsistencies or incorrect usage. This is the default and a very handy debugging aid, since the core file represents the time of failure, rather than when the bogus pointer was used. D "Dump". malloc() will dump statistics to the file ./malloc.out, if it already exists, at exit. This option requires the library to have been compiled with -DMALLOC_STATS in order to have any effect. F "Freeguard". Enable use after free detection. Unused pages on the freelist are read and write protected to cause a segmentation fault upon access. This will also switch off the delayed freeing of chunks, reducing random behaviour but detecting double free() calls as early as possible. This option is intended for debugging rather than improved security (use the U option for security). G "Guard". Enable guard pages. Each page size or larger allocation is followed by a guard page that will cause a segmentation fault upon any access. H "Hint". Pass a hint to the kernel about pages we don't use. If the machine is paging a lot this may help a bit. J "Junk". Fill some junk into the area allocated. Currently junk is bytes of 0xd0 when allocating; this is pronounced "Duh". :-) Freed chunks are filled with 0xdf. j "Don't Junk". By default, small chunks are always junked, and the first part of pages is junked after free. This option ensures that no junking is performed. P "Move allocations within a page." Allocations larger than half a page but smaller than a page are aligned to the end of a page to catch buffer overruns in more cases. This is the default. R "realloc". Always reallocate when realloc() is called, even if the initial allocation was big enough. This can substantially aid in compacting memory. S Enable all options suitable for security auditing. U "Free unmap". Enable use after free protection for larger alloca- tions. Unused pages on the freelist are read and write protected to cause a segmentation fault upon access. X "xmalloc". Rather than return failure, abort(3) the program with a diagnostic message on stderr. It is the intention that this op- tion be set at compile time by including in the source: extern char *malloc_options; malloc_options = "X"; Note that this will cause code that is supposed to handle out-of- memory conditions gracefully to abort instead. < "Half the cache size". Decrease the size of the free page cache by a factor of two. > "Double the cache size". Increase the size of the free page cache by a factor of two. So to set a systemwide reduction of the cache to a quarter of the default size and use guard pages: # ln -s 'G<<' /etc/malloc.conf The flags are mostly for testing and debugging. If a program changes behavior if any of these options (except X) are used, it is buggy. The default number of free pages cached is 64.
brk(2), mmap(2), munmap(2), alloca(3), getpagesize(3), posix_memalign(3), sysconf(3)
The malloc(), calloc(), realloc() and free() functions conform to ANSI X3.159-1989 ("ANSI C89"). If size or nmemb are 0, the return value is implementation defined; other conforming implementations may return NULL in this case. The standard does not require calloc() to check for integer overflow, but most modern implementations provide this check. The MALLOC_OPTIONS environment variable, the file /etc/malloc.conf, and the DIAGNOSTICS output are extensions to the standard.
A free() internal kernel function and a antecessor to malloc(), alloc(), first appeared in Version 1 AT&T UNIX. C library functions alloc() and free() appeared in Version 6 AT&T UNIX. The functions malloc(), calloc() and realloc() first appeared in Version 7 AT&T UNIX. A new implementation by Chris Kingsley was introduced in 4.2BSD, followed by a complete rewrite by Poul-Henning Kamp which appeared in FreeBSD 2.2 and was included in OpenBSD 2.0. These implementations were all sbrk(2) based. In OpenBSD 3.8, Thierry Deval rewrote malloc to use the mmap(2) system call, making the page addresses returned by malloc random. A rewrite by Otto Moerbeek introducing a new central data structure and more randomisation appeared in OpenBSD 4.4. The reallocarray() function appeared in OpenBSD 5.6. The recallocarray() function appeared in OpenBSD 6.1. The freezero() function appeared in OpenBSD 6.2. The cfree() function appeared in SunOS 4.x.
It should be noted explicitly that the pointer passed to realloc() (and reallocarray()) is invalid, and any attempt to use it Undefined Behaviour, after the function succeeded, and after all calls to free(). When using malloc(), be wary of signed integer and size_t overflow espe- cially when there is multiplication in the size argument. Signed integer overflow will cause undefined behavior which compilers typically handle by wrapping back around to negative numbers. Depending on the input, this can result in allocating more or less memory than in- tended. An unsigned overflow has defined behavior which will wrap back around and return less memory than intended. A signed or unsigned integer overflow is a security risk if less memory is returned than intended. Subsequent code may corrupt the heap by writ- ing beyond the memory that was allocated. An attacker may be able to lev- erage this heap corruption to execute arbitrary code. Consider using calloc(), reallocarray() or recallocarray() instead of us- ing multiplication in malloc() and realloc() to avoid these problems on OpenBSD. MirBSD #10-current November 7, 2020 6