1malloc(3)                  Library Functions Manual                  malloc(3)
2
3
4

NAME

6       malloc, free, calloc, realloc, reallocarray - allocate and free dynamic
7       memory
8

LIBRARY

10       Standard C library (libc, -lc)
11

SYNOPSIS

13       #include <stdlib.h>
14
15       void *malloc(size_t size);
16       void free(void *ptr);
17       void *calloc(size_t nmemb, size_t size);
18       void *realloc(void *ptr, size_t size);
19       void *reallocarray(void *ptr, size_t nmemb, size_t size);
20
21   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
22
23       reallocarray():
24           Since glibc 2.29:
25               _DEFAULT_SOURCE
26           glibc 2.28 and earlier:
27               _GNU_SOURCE
28

DESCRIPTION

30   malloc()
31       The malloc() function allocates size bytes and returns a pointer to the
32       allocated  memory.   The memory is not initialized.  If size is 0, then
33       malloc() returns a unique pointer value that can later be  successfully
34       passed to free().  (See "Nonportable behavior" for portability issues.)
35
36   free()
37       The  free()  function  frees  the memory space pointed to by ptr, which
38       must have been returned by a previous call to malloc() or related func‐
39       tions.  Otherwise, or if ptr has already been freed, undefined behavior
40       occurs.  If ptr is NULL, no operation is performed.
41
42   calloc()
43       The calloc() function allocates memory for an array of  nmemb  elements
44       of  size bytes each and returns a pointer to the allocated memory.  The
45       memory is set to zero.  If nmemb or size is 0, then calloc() returns  a
46       unique pointer value that can later be successfully passed to free().
47
48       If  the  multiplication of nmemb and size would result in integer over‐
49       flow, then calloc() returns an error.  By contrast, an integer overflow
50       would  not  be detected in the following call to malloc(), with the re‐
51       sult that an incorrectly sized block of memory would be allocated:
52
53           malloc(nmemb * size);
54
55   realloc()
56       The realloc() function changes the size of the memory block pointed  to
57       by  ptr to size bytes.  The contents of the memory will be unchanged in
58       the range from the start of the region up to the minimum of the old and
59       new sizes.  If the new size is larger than the old size, the added mem‐
60       ory will not be initialized.
61
62       If ptr is NULL, then the call is equivalent to  malloc(size),  for  all
63       values of size.
64
65       If size is equal to zero, and ptr is not NULL, then the call is equiva‐
66       lent to free(ptr) (but see "Nonportable behavior" for  portability  is‐
67       sues).
68
69       Unless  ptr  is  NULL, it must have been returned by an earlier call to
70       malloc or related functions.  If the  area  pointed  to  was  moved,  a
71       free(ptr) is done.
72
73   reallocarray()
74       The  reallocarray()  function  changes the size of (and possibly moves)
75       the memory block pointed to by ptr to be large enough for an  array  of
76       nmemb  elements,  each of which is size bytes.  It is equivalent to the
77       call
78
79           realloc(ptr, nmemb * size);
80
81       However, unlike that realloc() call, reallocarray() fails safely in the
82       case  where the multiplication would overflow.  If such an overflow oc‐
83       curs, reallocarray() returns an error.
84

RETURN VALUE

86       The malloc(), calloc(), realloc(), and reallocarray() functions  return
87       a  pointer  to  the allocated memory, which is suitably aligned for any
88       type that fits into the requested size or less.  On error, these  func‐
89       tions  return  NULL  and  set  errno.  Attempting to allocate more than
90       PTRDIFF_MAX bytes is considered an error, as an object that large could
91       cause later pointer subtraction to overflow.
92
93       The free() function returns no value, and preserves errno.
94
95       The  realloc()  and  reallocarray() functions return NULL if ptr is not
96       NULL and the requested size is zero; this is not considered  an  error.
97       (See  "Nonportable  behavior"  for portability issues.)  Otherwise, the
98       returned pointer may be the same as ptr if the allocation was not moved
99       (e.g.,  there was room to expand the allocation in-place), or different
100       from ptr if the allocation was moved to a new address.  If these  func‐
101       tions  fail,  the  original block is left untouched; it is not freed or
102       moved.
103

ERRORS

105       calloc(), malloc(), realloc(), and reallocarray()  can  fail  with  the
106       following error:
107
108       ENOMEM Out  of  memory.  Possibly, the application hit the RLIMIT_AS or
109              RLIMIT_DATA limit described in getrlimit(2).
110

ATTRIBUTES

112       For an  explanation  of  the  terms  used  in  this  section,  see  at‐
113       tributes(7).
114
115       ┌────────────────────────────────────────────┬───────────────┬─────────┐
116Interface                                   Attribute     Value   
117       ├────────────────────────────────────────────┼───────────────┼─────────┤
118malloc(), free(), calloc(), realloc()       │ Thread safety │ MT-Safe │
119       └────────────────────────────────────────────┴───────────────┴─────────┘
120

STANDARDS

122       malloc()
123       free()
124       calloc()
125       realloc()
126              C11, POSIX.1-2008.
127
128       reallocarray()
129              None.
130

HISTORY

132       malloc()
133       free()
134       calloc()
135       realloc()
136              POSIX.1-2001, C89.
137
138       reallocarray()
139              glibc 2.26.  OpenBSD 5.6, FreeBSD 11.0.
140
141       malloc()  and related functions rejected sizes greater than PTRDIFF_MAX
142       starting in glibc 2.30.
143
144       free() preserved errno starting in glibc 2.33.
145

NOTES

147       By default, Linux follows an  optimistic  memory  allocation  strategy.
148       This  means  that  when malloc() returns non-NULL there is no guarantee
149       that the memory really is available.  In case it  turns  out  that  the
150       system  is  out  of memory, one or more processes will be killed by the
151       OOM  killer.   For   more   information,   see   the   description   of
152       /proc/sys/vm/overcommit_memory and /proc/sys/vm/oom_adj in proc(5), and
153       the  Linux  kernel  source  file   Documentation/vm/overcommit-account‐
154       ing.rst.
155
156       Normally, malloc() allocates memory from the heap, and adjusts the size
157       of the heap as required, using sbrk(2).  When allocating blocks of mem‐
158       ory larger than MMAP_THRESHOLD bytes, the glibc malloc() implementation
159       allocates the memory as a  private  anonymous  mapping  using  mmap(2).
160       MMAP_THRESHOLD  is  128 kB  by  default,  but  is adjustable using mal‐
161       lopt(3).  Prior to Linux 4.7 allocations performed using  mmap(2)  were
162       unaffected  by  the  RLIMIT_DATA  resource limit; since Linux 4.7, this
163       limit is also enforced for allocations performed using mmap(2).
164
165       To avoid corruption in multithreaded applications, mutexes are used in‐
166       ternally  to  protect the memory-management data structures employed by
167       these functions.  In a multithreaded application in which  threads  si‐
168       multaneously  allocate  and  free memory, there could be contention for
169       these mutexes.  To scalably handle memory allocation  in  multithreaded
170       applications,  glibc creates additional memory allocation arenas if mu‐
171       tex contention is detected.  Each arena is a  large  region  of  memory
172       that  is  internally allocated by the system (using brk(2) or mmap(2)),
173       and managed with its own mutexes.
174
175       If your program uses a private memory allocator, it should do so by re‐
176       placing  malloc(),  free(),  calloc(),  and realloc().  The replacement
177       functions must implement the documented glibc behaviors, including  er‐
178       rno  handling, size-zero allocations, and overflow checking; otherwise,
179       other library routines may crash or operate incorrectly.  For  example,
180       if the replacement free() does not preserve errno, then seemingly unre‐
181       lated library routines may fail without having a valid reason in errno.
182       Private  memory  allocators  may also need to replace other glibc func‐
183       tions; see "Replacing malloc" in the glibc manual for details.
184
185       Crashes in memory allocators are almost always related to heap  corrup‐
186       tion, such as overflowing an allocated chunk or freeing the same point‐
187       er twice.
188
189       The malloc() implementation is tunable via environment  variables;  see
190       mallopt(3) for details.
191
192   Nonportable behavior
193       The  behavior  of  these  functions  when the requested size is zero is
194       glibc specific; other implementations may return NULL  without  setting
195       errno,  and portable POSIX programs should tolerate such behavior.  See
196       realloc(3p).
197
198       POSIX requires memory allocators to set errno upon  failure.   However,
199       the C standard does not require this, and applications portable to non-
200       POSIX platforms should not assume this.
201
202       Portable programs should not use private memory  allocators,  as  POSIX
203       and  the  C standard do not allow replacement of malloc(), free(), cal‐
204       loc(), and realloc().
205

EXAMPLES

207       #include <err.h>
208       #include <stddef.h>
209       #include <stdio.h>
210       #include <stdlib.h>
211       #include <string.h>
212
213       #define MALLOCARRAY(n, type)  ((type *) my_mallocarray(n, sizeof(type)))
214       #define MALLOC(type)          MALLOCARRAY(1, type)
215
216       static inline void *my_mallocarray(size_t nmemb, size_t size);
217
218       int
219       main(void)
220       {
221           char  *p;
222
223           p = MALLOCARRAY(32, char);
224           if (p == NULL)
225               err(EXIT_FAILURE, "malloc");
226
227           strlcpy(p, "foo", 32);
228           puts(p);
229       }
230
231       static inline void *
232       my_mallocarray(size_t nmemb, size_t size)
233       {
234           return reallocarray(NULL, nmemb, size);
235       }
236

SEE ALSO

238       valgrind(1), brk(2), mmap(2), alloca(3), malloc_get_state(3),
239       malloc_info(3), malloc_trim(3), malloc_usable_size(3), mallopt(3),
240       mcheck(3), mtrace(3), posix_memalign(3)
241
242       For details of the GNU C library implementation, see
243https://sourceware.org/glibc/wiki/MallocInternals⟩.
244
245
246
247Linux man-pages 6.04              2023-03-30                         malloc(3)
Impressum