malloc.3: ffix
[man-pages.git] / man3 / malloc.3
blobb558c18ae05d5e3aacd5cda72405e233e29e510e
1 .\" Copyright (c) 1993 by Thomas Koenig (ig25@rz.uni-karlsruhe.de)
2 .\" and Copyright i2007, 2012, 2018, Michael Kerrisk <mtk.manpages@gmail.com>
3 .\"
4 .\" %%%LICENSE_START(VERBATIM)
5 .\" Permission is granted to make and distribute verbatim copies of this
6 .\" manual provided the copyright notice and this permission notice are
7 .\" preserved on all copies.
8 .\"
9 .\" Permission is granted to copy and distribute modified versions of this
10 .\" manual under the conditions for verbatim copying, provided that the
11 .\" entire resulting derived work is distributed under the terms of a
12 .\" permission notice identical to this one.
13 .\"
14 .\" Since the Linux kernel and libraries are constantly changing, this
15 .\" manual page may be incorrect or out-of-date.  The author(s) assume no
16 .\" responsibility for errors or omissions, or for damages resulting from
17 .\" the use of the information contained herein.  The author(s) may not
18 .\" have taken the same level of care in the production of this manual,
19 .\" which is licensed free of charge, as they might when working
20 .\" professionally.
21 .\"
22 .\" Formatted or processed versions of this manual, if unaccompanied by
23 .\" the source, must acknowledge the copyright and authors of this work.
24 .\" %%%LICENSE_END
25 .\"
26 .\" Modified Sat Jul 24 19:00:59 1993 by Rik Faith (faith@cs.unc.edu)
27 .\" Clarification concerning realloc, iwj10@cus.cam.ac.uk (Ian Jackson), 950701
28 .\" Documented MALLOC_CHECK_, Wolfram Gloger (wmglo@dent.med.uni-muenchen.de)
29 .\" 2007-09-15 mtk: added notes on malloc()'s use of sbrk() and mmap().
30 .\"
31 .\" FIXME . Review http://austingroupbugs.net/view.php?id=374
32 .\" to see what changes are required on this page.
33 .\"
34 .TH MALLOC 3  2021-03-22 "GNU" "Linux Programmer's Manual"
35 .SH NAME
36 malloc, free, calloc, realloc, reallocarray \- allocate and free dynamic memory
37 .SH SYNOPSIS
38 .nf
39 .B #include <stdlib.h>
40 .PP
41 .BI "void *malloc(size_t " "size" );
42 .BI "void free(void " "*ptr" );
43 .BI "void *calloc(size_t " "nmemb" ", size_t " "size" );
44 .BI "void *realloc(void " "*ptr" ", size_t "  "size" );
45 .BI "void *reallocarray(void " "*ptr" ", size_t " nmemb ", size_t "  "size" );
46 .fi
47 .PP
48 .RS -4
49 Feature Test Macro Requirements for glibc (see
50 .BR feature_test_macros (7)):
51 .RE
52 .PP
53 .BR reallocarray ():
54 .nf
55     Since glibc 2.29:
56         _DEFAULT_SOURCE
57     Glibc 2.28 and earlier:
58         _GNU_SOURCE
59 .fi
60 .SH DESCRIPTION
61 .SS malloc()
62 The
63 .BR malloc ()
64 function allocates
65 .I size
66 bytes and returns a pointer to the allocated memory.
67 .IR "The memory is not initialized" .
69 .I size
70 is 0, then
71 .BR malloc ()
72 returns a unique pointer value that can later be successfully passed to
73 .BR free ().
74 (See "Nonportable behavior" for portability issues.)
75 .SS free()
76 The
77 .BR free ()
78 function frees the memory space pointed to by
79 .IR ptr ,
80 which must have been returned by a previous call to
81 .BR malloc ()
82 or related functions.
83 Otherwise, or if
84 .I ptr
85 has already been freed, undefined behavior occurs.
87 .I ptr
88 is NULL, no operation is performed.
89 .SS calloc()
90 The
91 .BR calloc ()
92 function allocates memory for an array of
93 .I nmemb
94 elements of
95 .I size
96 bytes each and returns a pointer to the allocated memory.
97 The memory is set to zero.
99 .I nmemb
101 .I size
102 is 0, then
103 .BR calloc ()
104 returns a unique pointer value that can later be successfully passed to
105 .BR free ().
107 If the multiplication of
108 .I nmemb
110 .I size
111 would result in integer overflow, then
112 .BR calloc ()
113 returns an error.
114 By contrast,
115 an integer overflow would not be detected in the following call to
116 .BR malloc (),
117 with the result that an incorrectly sized block of memory would be allocated:
119 .in +4n
121 malloc(nmemb * size);
124 .SS realloc()
126 .BR realloc ()
127 function changes the size of the memory block pointed to by
128 .I ptr
130 .I size
131 bytes.
132 The contents will be unchanged in the range from the start of the region
133 up to the minimum of the old and new sizes.
134 If the new size is larger than the old size, the added memory will
135 .I not
136 be initialized.
139 .I ptr
140 is NULL, then the call is equivalent to
141 .IR malloc(size) ,
142 for all values of
143 .IR size .
146 .I size
147 is equal to zero,
149 .I ptr
150 is not NULL, then the call is equivalent to
151 .I free(ptr)
152 (but see "Nonportable behavior" for portability issues).
154 Unless
155 .I ptr
156 is NULL, it must have been returned by an earlier call to
157 .B malloc
158 or related functions.
159 If the area pointed to was moved, a
160 .I free(ptr)
161 is done.
162 .SS reallocarray()
164 .BR reallocarray ()
165 function changes the size of the memory block pointed to by
166 .I ptr
167 to be large enough for an array of
168 .I nmemb
169 elements, each of which is
170 .I size
171 bytes.
172 It is equivalent to the call
174 .in +4n
176 realloc(ptr, nmemb * size);
180 However, unlike that
181 .BR realloc ()
182 call,
183 .BR reallocarray ()
184 fails safely in the case where the multiplication would overflow.
185 If such an overflow occurs,
186 .BR reallocarray ()
187 returns an error.
188 .SH RETURN VALUE
190 .BR malloc (),
191 .BR calloc (),
192 .BR realloc (),
194 .BR reallocarray ()
195 functions return a pointer to the allocated memory,
196 which is suitably aligned for any type that fits into
197 the requested size or less.
198 On error, these functions return NULL and set
199 .IR errno .
200 Attempting to allocate more than
201 .B PTRDIFF_MAX
202 bytes is considered an error, as an object that large
203 could cause later pointer subtraction to overflow.
206 .BR free ()
207 function returns no value, and preserves
208 .IR errno .
211 .BR realloc ()
213 .BR reallocarray ()
214 functions return NULL if
215 .I ptr
216 is not NULL and the requested size is zero;
217 this is not considered an error.
218 (See "Nonportable behavior" for portability issues.)
219 Otherwise, the returned pointer may be the same as
220 .IR ptr
221 if the allocation was not moved
222 (e.g., there was room to expand the allocation in-place), or different from
223 .IR ptr
224 if the allocation was moved to a new address.
225 If these functions fail,
226 the original block is left untouched; it is not freed or moved.
227 .SH ERRORS
228 .BR calloc (),
229 .BR malloc (),
230 .BR realloc (),
232 .BR reallocarray ()
233 can fail with the following error:
235 .B ENOMEM
236 Out of memory.
237 Possibly, the application hit the
238 .BR RLIMIT_AS
240 .BR RLIMIT_DATA
241 limit described in
242 .BR getrlimit (2).
243 .SH VERSIONS
244 .BR reallocarray ()
245 first appeared in glibc in version 2.26.
247 .BR malloc ()
248 and related functions rejected sizes greater than
249 .B PTRDIFF_MAX
250 starting in glibc 2.30.
252 .BR free ()
253 preserved
254 .I errno
255 starting in glibc 2.33.
256 .SH ATTRIBUTES
257 For an explanation of the terms used in this section, see
258 .BR attributes (7).
259 .ad l
262 allbox;
263 lbx lb lb
264 l l l.
265 Interface       Attribute       Value
267 .BR malloc (),
268 .BR free (),
269 .BR calloc (),
270 .BR realloc ()
271 T}      Thread safety   MT-Safe
275 .sp 1
276 .SH CONFORMING TO
277 .BR malloc (),
278 .BR free (),
279 .BR calloc (),
280 .BR realloc ():
281 POSIX.1-2001, POSIX.1-2008, C89, C99.
283 .BR reallocarray ()
284 is a nonstandard extension that first appeared in OpenBSD 5.6 and FreeBSD 11.0.
285 .SH NOTES
286 By default, Linux follows an optimistic memory allocation strategy.
287 This means that when
288 .BR malloc ()
289 returns non-NULL there is no guarantee that the memory really
290 is available.
291 In case it turns out that the system is out of memory,
292 one or more processes will be killed by the OOM killer.
293 For more information, see the description of
294 .IR /proc/sys/vm/overcommit_memory
296 .IR /proc/sys/vm/oom_adj
298 .BR proc (5),
299 and the Linux kernel source file
300 .IR Documentation/vm/overcommit\-accounting.rst .
302 Normally,
303 .BR malloc ()
304 allocates memory from the heap, and adjusts the size of the heap
305 as required, using
306 .BR sbrk (2).
307 When allocating blocks of memory larger than
308 .B MMAP_THRESHOLD
309 bytes, the glibc
310 .BR malloc ()
311 implementation allocates the memory as a private anonymous mapping using
312 .BR mmap (2).
313 .B MMAP_THRESHOLD
314 is 128\ kB by default, but is adjustable using
315 .BR mallopt (3).
316 Prior to Linux 4.7
317 allocations performed using
318 .BR mmap (2)
319 were unaffected by the
320 .B RLIMIT_DATA
321 resource limit;
322 since Linux 4.7, this limit is also enforced for allocations performed using
323 .BR mmap (2).
325 To avoid corruption in multithreaded applications,
326 mutexes are used internally to protect the memory-management
327 data structures employed by these functions.
328 In a multithreaded application in which threads simultaneously
329 allocate and free memory,
330 there could be contention for these mutexes.
331 To scalably handle memory allocation in multithreaded applications,
332 glibc creates additional
333 .IR "memory allocation arenas"
334 if mutex contention is detected.
335 Each arena is a large region of memory that is internally allocated
336 by the system
337 (using
338 .BR brk (2)
340 .BR mmap (2)),
341 and managed with its own mutexes.
343 If your program uses a private memory allocator,
344 it should do so by replacing
345 .BR malloc (),
346 .BR free (),
347 .BR calloc (),
349 .BR realloc ().
350 The replacement functions must implement the documented glibc behaviors,
351 including
352 .I errno
353 handling, size-zero allocations, and overflow checking;
354 otherwise, other library routines may crash or operate incorrectly.
355 For example, if the replacement
356 .IR free ()
357 does not preserve errno, then seemingly unrelated library routines may
358 fail without having a valid reason in
359 .IR errno .
360 Private memory allocators may also need to replace other glibc functions;
361 see "Replacing malloc" in the glibc manual for details.
363 Crashes in memory allocators
364 are almost always related to heap corruption, such as overflowing
365 an allocated chunk or freeing the same pointer twice.
368 .BR malloc ()
369 implementation is tunable via environment variables; see
370 .BR mallopt (3)
371 for details.
372 .SS Nonportable behavior
373 The behavior of
374 these functions when the requested size is zero
375 is glibc specific;
376 other implementations may return NULL without setting
377 .IR errno ,
378 and portable POSIX programs should tolerate such behavior.
380 .BR realloc (3p).
382 POSIX requires memory allocators
383 to set
384 .I errno
385 upon failure.
386 However, the C standard does not require this, and applications
387 portable to non-POSIX platforms should not assume this.
389 Portable programs should not use private memory allocators,
390 as POSIX and the C standard do not allow replacement of
391 .BR malloc (),
392 .BR free (),
393 .BR calloc (),
395 .BR realloc ().
396 .SH SEE ALSO
397 .\" http://g.oswego.edu/dl/html/malloc.html
398 .\" A Memory Allocator - by Doug Lea
400 .\" http://www.bozemanpass.com/info/linux/malloc/Linux_Heap_Contention.html
401 .\" Linux Heap, Contention in free() - David Boreham
403 .\" http://www.citi.umich.edu/projects/linux-scalability/reports/malloc.html
404 .\" malloc() Performance in a Multithreaded Linux Environment -
405 .\"     Check Lever, David Boreham
407 .ad l
409 .BR valgrind (1),
410 .BR brk (2),
411 .BR mmap (2),
412 .BR alloca (3),
413 .BR malloc_get_state (3),
414 .BR malloc_info (3),
415 .BR malloc_trim (3),
416 .BR malloc_usable_size (3),
417 .BR mallopt (3),
418 .BR mcheck (3),
419 .BR mtrace (3),
420 .BR posix_memalign (3)
422 For details of the GNU C library implementation, see
423 .UR https://sourceware.org/glibc/wiki/MallocInternals
424 .UE .