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 *_Nullable ptr);
17       void *calloc(size_t nmemb, size_t size);
18       void *realloc(void *_Nullable ptr, size_t size);
19       void *reallocarray(void *_Nullable 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).   Another  reason
110              could  be  that  the  number  of  mappings created by the caller
111              process      exceeded      the      limit      specified      by
112              /proc/sys/vm/max_map_count.
113

ATTRIBUTES

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

STANDARDS

125       malloc()
126       free()
127       calloc()
128       realloc()
129              C11, POSIX.1-2008.
130
131       reallocarray()
132              None.
133

HISTORY

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

NOTES

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

EXAMPLES

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

SEE ALSO

243       valgrind(1), brk(2), mmap(2), alloca(3), malloc_get_state(3),
244       malloc_info(3), malloc_trim(3), malloc_usable_size(3), mallopt(3),
245       mcheck(3), mtrace(3), posix_memalign(3)
246
247       For details of the GNU C library implementation, see
248https://sourceware.org/glibc/wiki/MallocInternals⟩.
249
250
251
252Linux man-pages 6.05              2023-07-20                         malloc(3)
Impressum