OpenBSD manual page server

Manual Page Search Parameters

MALLOC(3) Library Functions Manual MALLOC(3)

malloc, calloc, realloc, free, cfreememory 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
cfree(void *ptr);

char * malloc_options;

The () function allocates uninitialized space for an object whose size is specified by size. The malloc() function maintains multiple lists of free blocks according 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 or larger, the memory returned will be page-aligned.

Allocation of a zero size object returns a pointer to a zero size object. This zero size object is access protected, so any access to it will generate an exception (SIGSEGV). Many zero-sized objects can be placed consecutively in shared protected pages. The minimum size of the protection on each object is suitably aligned and sized as previously stated, but the protection may extend further depending on where in a protected zone the object lands.

When using () be careful to avoid the following idiom:

if ((p = malloc(num * size)) == NULL)
	err(1, "malloc");

The multiplication may lead to an integer overflow. To avoid this, () is recommended.

If () must be used, be sure to test for overflow:

if (size && num > SIZE_MAX / size) {
	errno = ENOMEM;
	err(1, "overflow");
}

The () function allocates space for an array of nmemb objects, each of whose size is size. The space is initialized to zero. The use of calloc() is strongly encouraged when allocating multiple sized objects in order to avoid possible integer overflows.

The () 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.

A () function is also provided for compatibility with old systems and other malloc libraries; it is simply an alias for free().

The () 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 portion of the object is indeterminate and uninitialized. If ptr is a null pointer, the realloc() function behaves like the malloc() function for the specified size. If the space cannot be allocated, the object pointed to by ptr is unchanged. If size is zero and ptr is not a null pointer, the object it points to is freed and a new zero size object is returned.

When using () 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 () 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) {
	...

Malloc will first look for a symbolic link called /etc/malloc.conf and next check the environment for a variable called MALLOC_OPTIONS and finally for the global variable malloc_options and scan them for flags in that order. Flags are single letters, uppercase means on, lowercase means off.

“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.
“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.
“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).
“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.
“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.
“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.
“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.
“realloc”. Always reallocate when realloc() is called, even if the initial allocation was big enough. This can substantially aid in compacting memory.
Enable all options suitable for security auditing.
“Free unmap”. Enable use after free protection for larger allocations. Unused pages on the freelist are read and write protected to cause a segmentation fault upon access.
“xmalloc”. Rather than return failure, abort(3) the program with a diagnostic message on stderr. It is the intention that this option 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.

“Zero”. Fill some junk into the area allocated (see J), except for the exact length the user asked for, which is zeroed.
“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.

The malloc() and calloc() functions return a pointer to the allocated space if successful; otherwise, a null pointer is returned and errno is set to ENOMEM.

The free() and cfree() functions return no value.

The realloc() function returns a pointer to the (possibly moved) allocated space if successful; otherwise, a null pointer is returned and errno is set to ENOMEM.

See above.

/etc/malloc.conf
symbolic link to filename containing option flags

If malloc(), calloc(), realloc(), or free() detect an error condition, a message will be printed to file descriptor 2 (not using stdio). Errors will result in the process being aborted, unless the a option 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(), calloc(), or realloc() 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() or realloc() 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() or realloc() 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 use any of the malloc() functions nor utilize 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.

brk(2), mmap(2), munmap(2), alloca(3), getpagesize(3), posix_memalign(3)

The malloc() function conforms to ANSI X3.159-1989 (“ANSI C89”).

A free() internal kernel function and a predecessor 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 randomization appeared in OpenBSD 4.4.

July 18, 2013 OpenBSD-5.4