File: malloc.3

package info (click to toggle)
manpages 6.15-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 20,184 kB
  • sloc: sh: 575; python: 222; perl: 190; makefile: 29; lisp: 22
file content (532 lines) | stat: -rw-r--r-- 12,283 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
'\" t
.\" Copyright, the authors of the Linux man-pages project
.\"
.\" SPDX-License-Identifier: Linux-man-pages-copyleft
.\"
.\" FIXME . Review http://austingroupbugs.net/view.php?id=374
.\" to see what changes are required on this page.
.\"
.TH malloc 3 2025-07-20 "Linux man-pages (unreleased)"
.SH NAME
malloc, free, calloc, realloc, reallocarray \- allocate and free dynamic memory
.SH LIBRARY
Standard C library
.RI ( libc ,\~ \-lc )
.SH SYNOPSIS
.nf
.B #include <stdlib.h>
.P
.BI "void *malloc(size_t " size );
.BI "void free(void *_Nullable " p );
.BI "void *calloc(size_t " n ", size_t " size );
.BI "void *realloc(void *_Nullable " p ", size_t "  size );
.BI "void *reallocarray(void *_Nullable " p ", size_t " n ", size_t " size );
.fi
.P
.RS -4
Feature Test Macro Requirements for glibc (see
.BR feature_test_macros (7)):
.RE
.P
.BR reallocarray ():
.nf
    Since glibc 2.29:
        _DEFAULT_SOURCE
    glibc 2.28 and earlier:
        _GNU_SOURCE
.fi
.SH DESCRIPTION
.SS malloc()
The
.BR malloc ()
function allocates
.I size
bytes and returns a pointer to the allocated memory.
.IR "The memory is not initialized" .
If
.I size
is 0, then
.BR malloc ()
returns a unique pointer value that can later be successfully passed to
.BR free ().
(See "Nonportable behavior" for portability issues.)
.SS free()
The
.BR free ()
function frees the memory space pointed to by
.IR p ,
which must have been returned by a previous call to
.BR malloc ()
or related functions.
Otherwise, or if
.I p
has already been freed, undefined behavior occurs.
If
.I p
is NULL, no operation is performed.
.SS calloc()
The
.BR calloc ()
function allocates memory for an array of
.I n
elements of
.I size
bytes each and returns a pointer to the allocated memory.
The memory is set to zero.
If
.I n
or
.I size
is 0, then
.BR calloc ()
returns a unique pointer value that can later be successfully passed to
.BR free ().
.P
If the multiplication of
.I n
and
.I size
would result in integer overflow, then
.BR calloc ()
returns an error.
By contrast,
an integer overflow would not be detected in the following call to
.BR malloc (),
with the result that an incorrectly sized block of memory would be allocated:
.P
.in +4n
.EX
malloc(n * size);
.EE
.in
.SS realloc()
The
.BR realloc ()
function changes the size of the memory block pointed to by
.I p
to
.I size
bytes.
The contents of the memory
will be unchanged in the range from the start of the region
up to the minimum of the old and new sizes.
If the new size is larger than the old size, the added memory will
.I not
be initialized.
.P
If
.I p
is NULL, then the call is equivalent to
.IR malloc(size) ,
for all values of
.IR size .
.P
If
.I size
is equal to zero,
and
.I p
is not NULL, then the call is equivalent to
.I free(p)
(but see "Nonportable behavior" for portability issues).
.P
Unless
.I p
is NULL, it must have been returned by an earlier call to
.B malloc
or related functions.
If the area pointed to was moved, a
.I free(p)
is done.
.SS reallocarray()
The
.BR reallocarray ()
function changes the size of (and possibly moves)
the memory block pointed to by
.I p
to be large enough for an array of
.I n
elements, each of which is
.I size
bytes.
It is equivalent to the call
.P
.in +4n
.EX
realloc(p, n * size);
.EE
.in
.P
However, unlike that
.BR realloc ()
call,
.BR reallocarray ()
fails safely in the case where the multiplication would overflow.
If such an overflow occurs,
.BR reallocarray ()
returns an error.
.SH RETURN VALUE
The
.BR malloc (),
.BR calloc (),
.BR realloc (),
and
.BR reallocarray ()
functions return a pointer to the allocated memory,
which is suitably aligned for any type that fits into
the requested size or less.
On error, these functions return NULL and set
.IR errno .
Attempting to allocate more than
.B PTRDIFF_MAX
bytes is considered an error, as an object that large
could cause later pointer subtraction to overflow.
.P
The
.BR free ()
function returns no value, and preserves
.IR errno .
.P
The
.BR realloc ()
and
.BR reallocarray ()
functions return NULL if
.I p
is not NULL and the requested size is zero;
this is not considered an error.
(See "Nonportable behavior" for portability issues.)
Otherwise, the returned pointer may be the same as
.I p
if the allocation was not moved
(e.g., there was room to expand the allocation in-place), or different from
.I p
if the allocation was moved to a new address.
If these functions fail,
the original block is left untouched; it is not freed or moved.
.SH ERRORS
.BR calloc (),
.BR malloc (),
.BR realloc (),
and
.BR reallocarray ()
can fail with the following error:
.TP
.B ENOMEM
Out of memory.
Possibly, the application hit the
.B RLIMIT_AS
or
.B RLIMIT_DATA
limit described in
.BR getrlimit (2).
Another reason could be that
the number of mappings created by the caller process
exceeded the limit specified by
.IR /proc/sys/vm/max_map_count .
.SH ATTRIBUTES
For an explanation of the terms used in this section, see
.BR attributes (7).
.TS
allbox;
lbx lb lb
l l l.
Interface	Attribute	Value
T{
.na
.nh
.BR malloc (),
.BR free (),
.BR calloc (),
.BR realloc ()
T}	Thread safety	MT-Safe
.TE
.SH STANDARDS
.TP
.BR malloc ()
.TQ
.BR free ()
.TQ
.BR calloc ()
.TQ
.BR realloc ()
C23, POSIX.1-2024.
.TP
.BR reallocarray ()
POSIX.1-2024.
.SS realloc(p, 0)
The behavior of
.I realloc(p,\~0)
in glibc doesn't conform to any of
C99,
C11,
POSIX.1-2001,
POSIX.1-2004,
POSIX.1-2008,
POSIX.1-2013,
POSIX.1-2017,
or POSIX.1-2024.
The C17 specification was changed to make it conforming,
but that specification made it
impossible to write code that reliably
determines if the input pointer is freed after
.IR realloc(p,\~0) ,
and C23 changed it again to make this undefined behavior,
acknowledging that the C17 specification was broad enough that
undefined behavior wasn't worse than that.
.P
.BR reallocarray ()
suffers the same issues in glibc.
.P
musl libc and the BSDs conform to all versions of ISO C and POSIX.1.
.P
gnulib provides the
.I realloc-posix
module,
which provides wrappers
.BR realloc ()
and
.BR reallocarray ()
that conform to all versions of ISO C and POSIX.1.
.P
There's a proposal to standardize the BSD behavior:
.UR https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3621.txt
.UE .
.SH HISTORY
.TP
.BR malloc ()
.TQ
.BR free ()
.TQ
.BR calloc ()
.TQ
.BR realloc ()
POSIX.1-2001, C89.
.TP
.BR reallocarray ()
glibc 2.26.
OpenBSD 5.6, FreeBSD 11.0.
.P
.BR malloc ()
and related functions rejected sizes greater than
.B PTRDIFF_MAX
starting in glibc 2.30.
.P
.BR free ()
preserved
.I errno
starting in glibc 2.33.
.SS realloc(p,\~0)
C89 was ambiguous in its specification of
.IR realloc(p,\~0) .
C99 partially fixed this.
.P
The original implementation in glibc would have been conforming to C99.
However, and ironically,
trying to comply with C99 before the standard was released,
glibc changed its behavior in glibc 2.1.1 into something that ended up
not conforming to the final C99 specification
(but this is debated,
as the wording of the standard seems self-contradicting).
.SH NOTES
By default, Linux follows an optimistic memory allocation strategy.
This means that when
.BR malloc ()
returns non-NULL there is no guarantee that the memory really
is available.
In case it turns out that the system is out of memory,
one or more processes will be killed by the OOM killer.
For more information, see the description of
.I /proc/sys/vm/overcommit_memory
and
.I /proc/sys/vm/oom_adj
in
.BR proc (5),
and the Linux kernel source file
.IR Documentation/vm/overcommit\-accounting.rst .
.P
Normally,
.BR malloc ()
allocates memory from the heap, and adjusts the size of the heap
as required, using
.BR sbrk (2).
When allocating blocks of memory larger than
.B MMAP_THRESHOLD
bytes, the glibc
.BR malloc ()
implementation allocates the memory as a private anonymous mapping using
.BR mmap (2).
.B MMAP_THRESHOLD
is 128\ kB by default, but is adjustable using
.BR mallopt (3).
Prior to Linux 4.7
allocations performed using
.BR mmap (2)
were unaffected by the
.B RLIMIT_DATA
resource limit;
since Linux 4.7, this limit is also enforced for allocations performed using
.BR mmap (2).
.P
To avoid corruption in multithreaded applications,
mutexes are used internally to protect the memory-management
data structures employed by these functions.
In a multithreaded application in which threads simultaneously
allocate and free memory,
there could be contention for these mutexes.
To scalably handle memory allocation in multithreaded applications,
glibc creates additional
.I memory allocation arenas
if mutex contention is detected.
Each arena is a large region of memory that is internally allocated
by the system
(using
.BR brk (2)
or
.BR mmap (2)),
and managed with its own mutexes.
.P
If your program uses a private memory allocator,
it should do so by replacing
.BR malloc (),
.BR free (),
.BR calloc (),
and
.BR realloc ().
The replacement functions must implement the documented glibc behaviors,
including
.I errno
handling, size-zero allocations, and overflow checking;
otherwise, other library routines may crash or operate incorrectly.
For example, if the replacement
.IR free ()
does not preserve
.IR errno ,
then seemingly unrelated library routines may
fail without having a valid reason in
.IR errno .
Private memory allocators may also need to replace other glibc functions;
see "Replacing malloc" in the glibc manual for details.
.P
Crashes in memory allocators
are almost always related to heap corruption, such as overflowing
an allocated chunk or freeing the same pointer twice.
.P
The
.BR malloc ()
implementation is tunable via environment variables; see
.BR mallopt (3)
for details.
.SS Nonportable behavior
The behavior of
these functions when the requested size is zero
is glibc specific;
other implementations may return NULL without setting
.IR errno ,
and portable POSIX programs should tolerate such behavior.
See
.BR realloc (3p).
.P
POSIX requires memory allocators
to set
.I errno
upon failure.
However, the C standard does not require this, and applications
portable to non-POSIX platforms should not assume this.
.P
Portable programs should not use private memory allocators,
as POSIX and the C standard do not allow replacement of
.BR malloc (),
.BR free (),
.BR calloc (),
and
.BR realloc ().
.SH BUGS
Programmers would naturally expect by induction that
.I \%realloc(p,\~size)
is consistent with
.I free(p)
and
.IR malloc(size) ,
as that is the behavior in the general case.
This is not explicitly required by POSIX.1-2024 or C11,
but all conforming implementations are consistent with that.
.P
The glibc implementation of
.BR realloc ()
is not consistent with that,
and as a consequence,
it is dangerous to call
.I \%realloc(p,\~0)
in glibc.
.P
A trivial workaround for glibc is calling it as
.IR \%realloc(p,\~size?size:1) .
.P
The workaround for
.BR reallocarray ()
in glibc
\[em]which shares the same bug\[em]
would be
.IR \%reallocarray(p,\~n?n:1,\~size?size:1) .
.SH EXAMPLES
.EX
#include <err.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
\&
#define MALLOCARRAY(n, type)  ((type *) my_mallocarray(n, sizeof(type)))
#define MALLOC(type)          MALLOCARRAY(1, type)
\&
static inline void *my_mallocarray(size_t n, size_t size);
\&
int
main(void)
{
    char  *p;
\&
    p = MALLOCARRAY(32, char);
    if (p == NULL)
        err(EXIT_FAILURE, "malloc");
\&
    strlcpy(p, "foo", 32);
    puts(p);
}
\&
static inline void *
my_mallocarray(size_t n, size_t size)
{
    return reallocarray(NULL, n, size);
}
.EE
.SH SEE ALSO
.\" http://g.oswego.edu/dl/html/malloc.html
.\" A Memory Allocator - by Doug Lea
.\"
.\" http://www.bozemanpass.com/info/linux/malloc/Linux_Heap_Contention.html
.\" Linux Heap, Contention in free() - David Boreham
.\"
.\" http://www.citi.umich.edu/projects/linux-scalability/reports/malloc.html
.\" malloc() Performance in a Multithreaded Linux Environment -
.\"     Check Lever, David Boreham
.\"
.ad l
.nh
.BR valgrind (1),
.BR brk (2),
.BR mmap (2),
.BR alloca (3),
.BR malloc_get_state (3),
.BR malloc_info (3),
.BR malloc_trim (3),
.BR malloc_usable_size (3),
.BR mallopt (3),
.BR mcheck (3),
.BR mtrace (3),
.BR posix_memalign (3)
.P
For details of the GNU C library implementation, see
.UR https://sourceware.org/glibc/wiki/MallocInternals
.UE .