tzfile.5, tzselect.8: sync from tzdb upstream
[man-pages.git] / man3 / malloc.3
blob21f537dd5e2f14e3911cd97f436f2249352f1286
1 '\" t
2 .\" Copyright (c) 1993 by Thomas Koenig (ig25@rz.uni-karlsruhe.de)
3 .\" and Copyright i2007, 2012, 2018, Michael Kerrisk <mtk.manpages@gmail.com>
4 .\"
5 .\" SPDX-License-Identifier: Linux-man-pages-copyleft
6 .\"
7 .\" Modified Sat Jul 24 19:00:59 1993 by Rik Faith (faith@cs.unc.edu)
8 .\" Clarification concerning realloc, iwj10@cus.cam.ac.uk (Ian Jackson), 950701
9 .\" Documented MALLOC_CHECK_, Wolfram Gloger (wmglo@dent.med.uni-muenchen.de)
10 .\" 2007-09-15 mtk: added notes on malloc()'s use of sbrk() and mmap().
11 .\"
12 .\" FIXME . Review http://austingroupbugs.net/view.php?id=374
13 .\" to see what changes are required on this page.
14 .\"
15 .TH malloc 3 (date) "Linux man-pages (unreleased)"
16 .SH NAME
17 malloc, free, calloc, realloc, reallocarray \- allocate and free dynamic memory
18 .SH LIBRARY
19 Standard C library
20 .RI ( libc ", " \-lc )
21 .SH SYNOPSIS
22 .nf
23 .B #include <stdlib.h>
24 .PP
25 .BI "void *malloc(size_t " "size" );
26 .BI "void free(void " "*ptr" );
27 .BI "void *calloc(size_t " "nmemb" ", size_t " "size" );
28 .BI "void *realloc(void " "*ptr" ", size_t "  "size" );
29 .BI "void *reallocarray(void " "*ptr" ", size_t " nmemb ", size_t "  "size" );
30 .fi
31 .PP
32 .RS -4
33 Feature Test Macro Requirements for glibc (see
34 .BR feature_test_macros (7)):
35 .RE
36 .PP
37 .BR reallocarray ():
38 .nf
39     Since glibc 2.29:
40         _DEFAULT_SOURCE
41     glibc 2.28 and earlier:
42         _GNU_SOURCE
43 .fi
44 .SH DESCRIPTION
45 .SS malloc()
46 The
47 .BR malloc ()
48 function allocates
49 .I size
50 bytes and returns a pointer to the allocated memory.
51 .IR "The memory is not initialized" .
53 .I size
54 is 0, then
55 .BR malloc ()
56 returns a unique pointer value that can later be successfully passed to
57 .BR free ().
58 (See "Nonportable behavior" for portability issues.)
59 .SS free()
60 The
61 .BR free ()
62 function frees the memory space pointed to by
63 .IR ptr ,
64 which must have been returned by a previous call to
65 .BR malloc ()
66 or related functions.
67 Otherwise, or if
68 .I ptr
69 has already been freed, undefined behavior occurs.
71 .I ptr
72 is NULL, no operation is performed.
73 .SS calloc()
74 The
75 .BR calloc ()
76 function allocates memory for an array of
77 .I nmemb
78 elements of
79 .I size
80 bytes each and returns a pointer to the allocated memory.
81 The memory is set to zero.
83 .I nmemb
85 .I size
86 is 0, then
87 .BR calloc ()
88 returns a unique pointer value that can later be successfully passed to
89 .BR free ().
90 .PP
91 If the multiplication of
92 .I nmemb
93 and
94 .I size
95 would result in integer overflow, then
96 .BR calloc ()
97 returns an error.
98 By contrast,
99 an integer overflow would not be detected in the following call to
100 .BR malloc (),
101 with the result that an incorrectly sized block of memory would be allocated:
103 .in +4n
105 malloc(nmemb * size);
108 .SS realloc()
110 .BR realloc ()
111 function changes the size of the memory block pointed to by
112 .I ptr
114 .I size
115 bytes.
116 The contents of the memory
117 will be unchanged in the range from the start of the region
118 up to the minimum of the old and new sizes.
119 If the new size is larger than the old size, the added memory will
120 .I not
121 be initialized.
124 .I ptr
125 is NULL, then the call is equivalent to
126 .IR malloc(size) ,
127 for all values of
128 .IR size .
131 .I size
132 is equal to zero,
134 .I ptr
135 is not NULL, then the call is equivalent to
136 .I free(ptr)
137 (but see "Nonportable behavior" for portability issues).
139 Unless
140 .I ptr
141 is NULL, it must have been returned by an earlier call to
142 .B malloc
143 or related functions.
144 If the area pointed to was moved, a
145 .I free(ptr)
146 is done.
147 .SS reallocarray()
149 .BR reallocarray ()
150 function changes the size of (and possibly moves)
151 the memory block pointed to by
152 .I ptr
153 to be large enough for an array of
154 .I nmemb
155 elements, each of which is
156 .I size
157 bytes.
158 It is equivalent to the call
160 .in +4n
162 realloc(ptr, nmemb * size);
166 However, unlike that
167 .BR realloc ()
168 call,
169 .BR reallocarray ()
170 fails safely in the case where the multiplication would overflow.
171 If such an overflow occurs,
172 .BR reallocarray ()
173 returns an error.
174 .SH RETURN VALUE
176 .BR malloc (),
177 .BR calloc (),
178 .BR realloc (),
180 .BR reallocarray ()
181 functions return a pointer to the allocated memory,
182 which is suitably aligned for any type that fits into
183 the requested size or less.
184 On error, these functions return NULL and set
185 .IR errno .
186 Attempting to allocate more than
187 .B PTRDIFF_MAX
188 bytes is considered an error, as an object that large
189 could cause later pointer subtraction to overflow.
192 .BR free ()
193 function returns no value, and preserves
194 .IR errno .
197 .BR realloc ()
199 .BR reallocarray ()
200 functions return NULL if
201 .I ptr
202 is not NULL and the requested size is zero;
203 this is not considered an error.
204 (See "Nonportable behavior" for portability issues.)
205 Otherwise, the returned pointer may be the same as
206 .I ptr
207 if the allocation was not moved
208 (e.g., there was room to expand the allocation in-place), or different from
209 .I ptr
210 if the allocation was moved to a new address.
211 If these functions fail,
212 the original block is left untouched; it is not freed or moved.
213 .SH ERRORS
214 .BR calloc (),
215 .BR malloc (),
216 .BR realloc (),
218 .BR reallocarray ()
219 can fail with the following error:
221 .B ENOMEM
222 Out of memory.
223 Possibly, the application hit the
224 .B RLIMIT_AS
226 .B RLIMIT_DATA
227 limit described in
228 .BR getrlimit (2).
229 .SH VERSIONS
230 .BR reallocarray ()
231 was added in glibc 2.26.
233 .BR malloc ()
234 and related functions rejected sizes greater than
235 .B PTRDIFF_MAX
236 starting in glibc 2.30.
238 .BR free ()
239 preserved
240 .I errno
241 starting in glibc 2.33.
242 .SH ATTRIBUTES
243 For an explanation of the terms used in this section, see
244 .BR attributes (7).
245 .ad l
248 allbox;
249 lbx lb lb
250 l l l.
251 Interface       Attribute       Value
253 .BR malloc (),
254 .BR free (),
255 .BR calloc (),
256 .BR realloc ()
257 T}      Thread safety   MT-Safe
261 .sp 1
262 .SH STANDARDS
263 .BR malloc (),
264 .BR free (),
265 .BR calloc (),
266 .BR realloc ():
267 POSIX.1-2001, POSIX.1-2008, C99.
269 .BR reallocarray ()
270 is a nonstandard extension that first appeared in OpenBSD 5.6 and FreeBSD 11.0.
271 .SH NOTES
272 By default, Linux follows an optimistic memory allocation strategy.
273 This means that when
274 .BR malloc ()
275 returns non-NULL there is no guarantee that the memory really
276 is available.
277 In case it turns out that the system is out of memory,
278 one or more processes will be killed by the OOM killer.
279 For more information, see the description of
280 .I /proc/sys/vm/overcommit_memory
282 .I /proc/sys/vm/oom_adj
284 .BR proc (5),
285 and the Linux kernel source file
286 .IR Documentation/vm/overcommit\-accounting.rst .
288 Normally,
289 .BR malloc ()
290 allocates memory from the heap, and adjusts the size of the heap
291 as required, using
292 .BR sbrk (2).
293 When allocating blocks of memory larger than
294 .B MMAP_THRESHOLD
295 bytes, the glibc
296 .BR malloc ()
297 implementation allocates the memory as a private anonymous mapping using
298 .BR mmap (2).
299 .B MMAP_THRESHOLD
300 is 128\ kB by default, but is adjustable using
301 .BR mallopt (3).
302 Prior to Linux 4.7
303 allocations performed using
304 .BR mmap (2)
305 were unaffected by the
306 .B RLIMIT_DATA
307 resource limit;
308 since Linux 4.7, this limit is also enforced for allocations performed using
309 .BR mmap (2).
311 To avoid corruption in multithreaded applications,
312 mutexes are used internally to protect the memory-management
313 data structures employed by these functions.
314 In a multithreaded application in which threads simultaneously
315 allocate and free memory,
316 there could be contention for these mutexes.
317 To scalably handle memory allocation in multithreaded applications,
318 glibc creates additional
319 .I memory allocation arenas
320 if mutex contention is detected.
321 Each arena is a large region of memory that is internally allocated
322 by the system
323 (using
324 .BR brk (2)
326 .BR mmap (2)),
327 and managed with its own mutexes.
329 If your program uses a private memory allocator,
330 it should do so by replacing
331 .BR malloc (),
332 .BR free (),
333 .BR calloc (),
335 .BR realloc ().
336 The replacement functions must implement the documented glibc behaviors,
337 including
338 .I errno
339 handling, size-zero allocations, and overflow checking;
340 otherwise, other library routines may crash or operate incorrectly.
341 For example, if the replacement
342 .IR free ()
343 does not preserve
344 .IR errno ,
345 then seemingly unrelated library routines may
346 fail without having a valid reason in
347 .IR errno .
348 Private memory allocators may also need to replace other glibc functions;
349 see "Replacing malloc" in the glibc manual for details.
351 Crashes in memory allocators
352 are almost always related to heap corruption, such as overflowing
353 an allocated chunk or freeing the same pointer twice.
356 .BR malloc ()
357 implementation is tunable via environment variables; see
358 .BR mallopt (3)
359 for details.
360 .SS Nonportable behavior
361 The behavior of
362 these functions when the requested size is zero
363 is glibc specific;
364 other implementations may return NULL without setting
365 .IR errno ,
366 and portable POSIX programs should tolerate such behavior.
368 .BR realloc (3p).
370 POSIX requires memory allocators
371 to set
372 .I errno
373 upon failure.
374 However, the C standard does not require this, and applications
375 portable to non-POSIX platforms should not assume this.
377 Portable programs should not use private memory allocators,
378 as POSIX and the C standard do not allow replacement of
379 .BR malloc (),
380 .BR free (),
381 .BR calloc (),
383 .BR realloc ().
384 .SH EXAMPLES
386 #include <err.h>
387 #include <stddef.h>
388 #include <stdio.h>
389 #include <stdlib.h>
390 #include <string.h>
392 #define MALLOCARRAY(n, type)  ((type *) my_mallocarray(n, sizeof(type)))
393 #define MALLOC(type)          MALLOCARRAY(1, type)
395 static inline void *my_mallocarray(size_t nmemb, size_t size);
398 main(void)
400     char  *p;
402     p = MALLOCARRAY(32, char);
403     if (p == NULL)
404         err(EXIT_FAILURE, "malloc");
406     strlcpy(p, "foo", 32);
407     puts(p);
410 static inline void *
411 my_mallocarray(size_t nmemb, size_t size)
413     return reallocarray(NULL, nmemb, size);
416 .SH SEE ALSO
417 .\" http://g.oswego.edu/dl/html/malloc.html
418 .\" A Memory Allocator - by Doug Lea
420 .\" http://www.bozemanpass.com/info/linux/malloc/Linux_Heap_Contention.html
421 .\" Linux Heap, Contention in free() - David Boreham
423 .\" http://www.citi.umich.edu/projects/linux-scalability/reports/malloc.html
424 .\" malloc() Performance in a Multithreaded Linux Environment -
425 .\"     Check Lever, David Boreham
427 .ad l
429 .BR valgrind (1),
430 .BR brk (2),
431 .BR mmap (2),
432 .BR alloca (3),
433 .BR malloc_get_state (3),
434 .BR malloc_info (3),
435 .BR malloc_trim (3),
436 .BR malloc_usable_size (3),
437 .BR mallopt (3),
438 .BR mcheck (3),
439 .BR mtrace (3),
440 .BR posix_memalign (3)
442 For details of the GNU C library implementation, see
443 .UR https://sourceware.org/glibc/wiki/MallocInternals
444 .UE .