MALLOC(2) MALLOC(2) NAME malloc, free, realloc, calloc - memory allocator SYNOPSIS #include <u.h> #include <libc.h> void* malloc(long size) void free(void *ptr) void* realloc(void *ptr, long size) void* calloc(long nelem, long elsize) DESCRIPTION Malloc and free provide a simple memory allocation package. Malloc returns a pointer to a new block of at least size bytes. The block is suitably aligned for storage of any type of object. No two active pointers from malloc will have the same value. The argument to free is a pointer to a block previously allocated by malloc; this space is made available for fur- ther allocation. It is legal to free a null pointer; the effect is a no-op. Realloc changes the size of the block pointed to by ptr to size bytes and returns a pointer to the (possibly moved) block. The contents will be unchanged up to the lesser of the new and old sizes. The call realloc(0, size) means the same as `malloc(size)'. Calloc allocates space for an array of nelem elements of size elsize. The space is initialized to zeros. Free frees such a block. Alef Except for calloc, these routines are available from Alef; they use the same arena as alloc. Malloc and realloc exe- cute a check when they fail, rather than return nil. Memory returned by malloc is cleared. Realloc does not guarantee new memory is cleared unless ptr is nil. SOURCE /sys/src/libc/port/malloc.c SEE ALSO brk(2) MALLOC(2) MALLOC(2) DIAGNOSTICS Malloc, realloc and calloc return 0 if there is no available memory. Errstr is likely to be set. BUGS The different specification of calloc is bizarre. User errors can corrupt the storage arena. The most common gaffes are (1) freeing an already freed block, (2) storing beyond the bounds of an allocated block, and (3) freeing data that was not obtained from the allocator. When malloc and free detect such corruption, they abort.