1MALLOC(3) Library Functions Manual MALLOC(3)
2
3
4
6 malloc, free, realloc, calloc - main memory allocator
7
9 char *malloc(size)
10 unsigned size;
11
12 free(ptr)
13 char *ptr;
14
15 char *realloc(ptr, size)
16 char *ptr;
17 unsigned size;
18
19 char *calloc(nelem, elsize)
20 unsigned nelem, elsize;
21
23 Malloc and free provide a simple general-purpose memory allocation
24 package. Malloc returns a pointer to a block of at least size bytes
25 beginning on a word boundary.
26
27 The argument to free is a pointer to a block previously allocated by
28 malloc; this space is made available for further allocation, but its
29 contents are left undisturbed.
30
31 Needless to say, grave disorder will result if the space assigned by
32 malloc is overrun or if some random number is handed to free.
33
34 Malloc allocates the first big enough contiguous reach of free space
35 found in a circular search from the last block allocated or freed, coa‐
36 lescing adjacent free blocks as it searches. It calls sbrk (see
37 break(2)) to get more memory from the system when there is no suitable
38 space already free.
39
40 Realloc changes the size of the block pointed to by ptr to size bytes
41 and returns a pointer to the (possibly moved) block. The contents will
42 be unchanged up to the lesser of the new and old sizes.
43
44 Realloc also works if ptr points to a block freed since the last call
45 of malloc, realloc or calloc; thus sequences of free, malloc and real‐
46 loc can exploit the search strategy of malloc to do storage compaction.
47
48 Calloc allocates space for an array of nelem elements of size elsize.
49 The space is initialized to zeros.
50
51 Each of the allocation routines returns a pointer to space suitably
52 aligned (after possible pointer coercion) for storage of any type of
53 object.
54
56 Malloc, realloc and calloc return a null pointer (0) if there is no
57 available memory or if the arena has been detectably corrupted by stor‐
58 ing outside the bounds of a block. Malloc may be recompiled to check
59 the arena very stringently on every transaction; see the source code.
60
62 When realloc returns 0, the block pointed to by ptr may be destroyed.
63
64
65
66 MALLOC(3)