1MALLOC(3) Linux Programmer's Manual MALLOC(3)
2
3
4
6 calloc, malloc, free, realloc - Allocate and free dynamic memory
7
9 #include <stdlib.h>
10
11 void *calloc(size_t nmemb, size_t size);
12 void *malloc(size_t size);
13 void free(void *ptr);
14 void *realloc(void *ptr, size_t size);
15
17 calloc() allocates memory for an array of nmemb elements of size bytes
18 each and returns a pointer to the allocated memory. The memory is set
19 to zero.
20
21 malloc() allocates size bytes and returns a pointer to the allocated
22 memory. The memory is not cleared.
23
24 free() frees the memory space pointed to by ptr, which must have been
25 returned by a previous call to malloc(), calloc() or realloc(). Other‐
26 wise, or if free(ptr) has already been called before, undefined behav‐
27 iour occurs. If ptr is NULL, no operation is performed.
28
29 realloc() changes the size of the memory block pointed to by ptr to
30 size bytes. The contents will be unchanged to the minimum of the old
31 and new sizes; newly allocated memory will be uninitialized. If ptr is
32 NULL, the call is equivalent to malloc(size); if size is equal to zero,
33 the call is equivalent to free(ptr). Unless ptr is NULL, it must have
34 been returned by an earlier call to malloc(), calloc() or realloc().
35 If the area pointed to was moved, a free(ptr) is done.
36
38 For calloc() and malloc(), the value returned is a pointer to the allo‐
39 cated memory, which is suitably aligned for any kind of variable, or
40 NULL if the request fails.
41
42 free() returns no value.
43
44 realloc() returns a pointer to the newly allocated memory, which is
45 suitably aligned for any kind of variable and may be different from
46 ptr, or NULL if the request fails. If size was equal to 0, either NULL
47 or a pointer suitable to be passed to free() is returned. If realloc()
48 fails the original block is left untouched; it is not freed or moved.
49
51 C89, C99.
52
54 brk(2), posix_memalign(3)
55
57 The Unix98 standard requires malloc(), calloc(), and realloc() to set
58 errno to ENOMEM upon failure. Glibc assumes that this is done (and the
59 glibc versions of these routines do this); if you use a private malloc
60 implementation that does not set errno, then certain library routines
61 may fail without having a reason in errno.
62
63 Crashes in malloc(), calloc(), realloc(), or free() are almost always
64 related to heap corruption, such as overflowing an allocated chunk or
65 freeing the same pointer twice.
66
67 Recent versions of Linux libc (later than 5.4.23) and GNU libc (2.x)
68 include a malloc implementation which is tunable via environment vari‐
69 ables. When MALLOC_CHECK_ is set, a special (less efficient) implemen‐
70 tation is used which is designed to be tolerant against simple errors,
71