Debian Codegraph @

upstream/debian-trixie/man3/malloc.3

raw
1 '\" t
2 .\" Copyright (c) 1993 by Thomas Koenig ([email protected])
3 .\" and Copyright 2007, 2012, 2018, Michael Kerrisk <[email protected]>
4 .\"
5 .\" SPDX-License-Identifier: Linux-man-pages-copyleft
6 .\"
7 .\" Modified Sat Jul 24 19:00:59 1993 by Rik Faith ([email protected])
8 .\" Clarification concerning realloc, [email protected] (Ian Jackson), 950701
9 .\" Documented MALLOC_CHECK_, Wolfram Gloger ([email protected])
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 2024-05-02 "Linux man-pages 6.9.1"
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 .P
25 .BI "void *malloc(size_t " size );
26 .BI "void free(void *_Nullable " ptr );
27 .BI "void *calloc(size_t " nmemb ", size_t " size );
28 .BI "void *realloc(void *_Nullable " ptr ", size_t " size );
29 .BI "void *reallocarray(void *_Nullable " ptr ", size_t " nmemb ", size_t " size );
30 .fi
31 .P
32 .RS -4
33 Feature Test Macro Requirements for glibc (see
34 .BR feature_test_macros (7)):
35 .RE
36 .P
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" .
52 If
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.
70 If
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.
82 If
83 .I nmemb
84 or
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 .P
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:
102 .P
103 .in +4n
104 .EX
105 malloc(nmemb * size);
106 .EE
107 .in
108 .SS realloc()
109 The
110 .BR realloc ()
111 function changes the size of the memory block pointed to by
112 .I ptr
113 to
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.
122 .P
123 If
124 .I ptr
125 is NULL, then the call is equivalent to
126 .IR malloc(size) ,
127 for all values of
128 .IR size .
129 .P
130 If
131 .I size
132 is equal to zero,
133 and
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).
138 .P
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()
148 The
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
159 .P
160 .in +4n
161 .EX
162 realloc(ptr, nmemb * size);
163 .EE
164 .in
165 .P
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
175 The
176 .BR malloc (),
177 .BR calloc (),
178 .BR realloc (),
179 and
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.
190 .P
191 The
192 .BR free ()
193 function returns no value, and preserves
194 .IR errno .
195 .P
196 The
197 .BR realloc ()
198 and
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 (),
217 and
218 .BR reallocarray ()
219 can fail with the following error:
220 .TP
221 .B ENOMEM
222 Out of memory.
223 Possibly, the application hit the
224 .B RLIMIT_AS
225 or
226 .B RLIMIT_DATA
227 limit described in
228 .BR getrlimit (2).
229 Another reason could be that
230 the number of mappings created by the caller process
231 exceeded the limit specified by
232 .IR /proc/sys/vm/max_map_count .
233 .SH ATTRIBUTES
234 For an explanation of the terms used in this section, see
235 .BR attributes (7).
236 .TS
237 allbox;
238 lbx lb lb
239 l l l.
240 Interface Attribute Value
241 T{
242 .na
243 .nh
244 .BR malloc (),
245 .BR free (),
246 .BR calloc (),
247 .BR realloc ()
248 T} Thread safety MT-Safe
249 .TE
250 .SH STANDARDS
251 .TP
252 .BR malloc ()
253 .TQ
254 .BR free ()
255 .TQ
256 .BR calloc ()
257 .TQ
258 .BR realloc ()
259 C11, POSIX.1-2008.
260 .TP
261 .BR reallocarray ()
262 None.
263 .SH HISTORY
264 .TP
265 .BR malloc ()
266 .TQ
267 .BR free ()
268 .TQ
269 .BR calloc ()
270 .TQ
271 .BR realloc ()
272 POSIX.1-2001, C89.
273 .TP
274 .BR reallocarray ()
275 glibc 2.26.
276 OpenBSD 5.6, FreeBSD 11.0.
277 .P
278 .BR malloc ()
279 and related functions rejected sizes greater than
280 .B PTRDIFF_MAX
281 starting in glibc 2.30.
282 .P
283 .BR free ()
284 preserved
285 .I errno
286 starting in glibc 2.33.
287 .SH NOTES
288 By default, Linux follows an optimistic memory allocation strategy.
289 This means that when
290 .BR malloc ()
291 returns non-NULL there is no guarantee that the memory really
292 is available.
293 In case it turns out that the system is out of memory,
294 one or more processes will be killed by the OOM killer.
295 For more information, see the description of
296 .I /proc/sys/vm/overcommit_memory
297 and
298 .I /proc/sys/vm/oom_adj
299 in
300 .BR proc (5),
301 and the Linux kernel source file
302 .IR Documentation/vm/overcommit\-accounting.rst .
303 .P
304 Normally,
305 .BR malloc ()
306 allocates memory from the heap, and adjusts the size of the heap
307 as required, using
308 .BR sbrk (2).
309 When allocating blocks of memory larger than
310 .B MMAP_THRESHOLD
311 bytes, the glibc
312 .BR malloc ()
313 implementation allocates the memory as a private anonymous mapping using
314 .BR mmap (2).
315 .B MMAP_THRESHOLD
316 is 128\ kB by default, but is adjustable using
317 .BR mallopt (3).
318 Prior to Linux 4.7
319 allocations performed using
320 .BR mmap (2)
321 were unaffected by the
322 .B RLIMIT_DATA
323 resource limit;
324 since Linux 4.7, this limit is also enforced for allocations performed using
325 .BR mmap (2).
326 .P
327 To avoid corruption in multithreaded applications,
328 mutexes are used internally to protect the memory-management
329 data structures employed by these functions.
330 In a multithreaded application in which threads simultaneously
331 allocate and free memory,
332 there could be contention for these mutexes.
333 To scalably handle memory allocation in multithreaded applications,
334 glibc creates additional
335 .I memory allocation arenas
336 if mutex contention is detected.
337 Each arena is a large region of memory that is internally allocated
338 by the system
339 (using
340 .BR brk (2)
341 or
342 .BR mmap (2)),
343 and managed with its own mutexes.
344 .P
345 If your program uses a private memory allocator,
346 it should do so by replacing
347 .BR malloc (),
348 .BR free (),
349 .BR calloc (),
350 and
351 .BR realloc ().
352 The replacement functions must implement the documented glibc behaviors,
353 including
354 .I errno
355 handling, size-zero allocations, and overflow checking;
356 otherwise, other library routines may crash or operate incorrectly.
357 For example, if the replacement
358 .IR free ()
359 does not preserve
360 .IR errno ,
361 then seemingly unrelated library routines may
362 fail without having a valid reason in
363 .IR errno .
364 Private memory allocators may also need to replace other glibc functions;
365 see "Replacing malloc" in the glibc manual for details.
366 .P
367 Crashes in memory allocators
368 are almost always related to heap corruption, such as overflowing
369 an allocated chunk or freeing the same pointer twice.
370 .P
371 The
372 .BR malloc ()
373 implementation is tunable via environment variables; see
374 .BR mallopt (3)
375 for details.
376 .SS Nonportable behavior
377 The behavior of
378 these functions when the requested size is zero
379 is glibc specific;
380 other implementations may return NULL without setting
381 .IR errno ,
382 and portable POSIX programs should tolerate such behavior.
383 See
384 .BR realloc (3p).
385 .P
386 POSIX requires memory allocators
387 to set
388 .I errno
389 upon failure.
390 However, the C standard does not require this, and applications
391 portable to non-POSIX platforms should not assume this.
392 .P
393 Portable programs should not use private memory allocators,
394 as POSIX and the C standard do not allow replacement of
395 .BR malloc (),
396 .BR free (),
397 .BR calloc (),
398 and
399 .BR realloc ().
400 .SH EXAMPLES
401 .EX
402 #include <err.h>
403 #include <stddef.h>
404 #include <stdio.h>
405 #include <stdlib.h>
406 #include <string.h>
407 \&
408 #define MALLOCARRAY(n, type) ((type *) my_mallocarray(n, sizeof(type)))
409 #define MALLOC(type) MALLOCARRAY(1, type)
410 \&
411 static inline void *my_mallocarray(size_t nmemb, size_t size);
412 \&
413 int
414 main(void)
415 {
416 char *p;
417 \&
418 p = MALLOCARRAY(32, char);
419 if (p == NULL)
420 err(EXIT_FAILURE, "malloc");
421 \&
422 strlcpy(p, "foo", 32);
423 puts(p);
424 }
425 \&
426 static inline void *
427 my_mallocarray(size_t nmemb, size_t size)
428 {
429 return reallocarray(NULL, nmemb, size);
430 }
431 .EE
432 .SH SEE ALSO
433 .\" http://g.oswego.edu/dl/html/malloc.html
434 .\" A Memory Allocator - by Doug Lea
435 .\"
436 .\" http://www.bozemanpass.com/info/linux/malloc/Linux_Heap_Contention.html
437 .\" Linux Heap, Contention in free() - David Boreham
438 .\"
439 .\" http://www.citi.umich.edu/projects/linux-scalability/reports/malloc.html
440 .\" malloc() Performance in a Multithreaded Linux Environment -
441 .\" Check Lever, David Boreham
442 .\"
443 .ad l
444 .nh
445 .BR valgrind (1),
446 .BR brk (2),
447 .BR mmap (2),
448 .BR alloca (3),
449 .BR malloc_get_state (3),
450 .BR malloc_info (3),
451 .BR malloc_trim (3),
452 .BR malloc_usable_size (3),
453 .BR mallopt (3),
454 .BR mcheck (3),
455 .BR mtrace (3),
456 .BR posix_memalign (3)
457 .P
458 For details of the GNU C library implementation, see
459 .UR https://sourceware.org/glibc/wiki/MallocInternals
460 .UE .