2 .\" Copyright (c) 1980, 1991, 1993
3 .\" The Regents of the University of California. All rights reserved.
5 .\" This code is derived from software contributed to Berkeley by
6 .\" the American National Standards Committee X3, on Information
7 .\" Processing Systems.
9 .\" Redistribution and use in source and binary forms, with or without
10 .\" modification, are permitted provided that the following conditions
12 .\" 1. Redistributions of source code must retain the above copyright
13 .\" notice, this list of conditions and the following disclaimer.
14 .\" 2. Redistributions in binary form must reproduce the above copyright
15 .\" notice, this list of conditions and the following disclaimer in the
16 .\" documentation and/or other materials provided with the distribution.
17 .\" 3. Neither the name of the University nor the names of its contributors
18 .\" may be used to endorse or promote products derived from this software
19 .\" without specific prior written permission.
21 .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 .\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 .\" $OpenBSD: malloc.3,v 1.115 2017/05/15 18:05:34 tb Exp $
35 .Dd $Mdocdate: November 13 2017 $
46 .Nd memory allocation and deallocation
50 .Fn malloc "size_t size"
52 .Fn calloc "size_t nmemb" "size_t size"
54 .Fn realloc "void *ptr" "size_t size"
58 .Fn reallocarray "void *ptr" "size_t nmemb" "size_t size"
60 .Fn recallocarray "void *ptr" "size_t oldnmemb" "size_t nmemb" "size_t size"
62 .Fn freezero "void *ptr" "size_t size"
64 The standard functions
71 regions of memory to store values.
74 function allocates uninitialized space for an object of
77 The allocated space is suitably aligned (after possible pointer coercion) for
78 storage of any type of object.
82 function allocates space for an array of
84 objects, each of the specified
86 The space is initialized to zero.
90 function changes the size of the object pointed to by
94 bytes and returns a pointer to the (possibly moved) object.
99 it must be a pointer returned by an earlier call to an allocation or
100 reallocation function that was not freed in between.
101 The contents of the object are unchanged up to the lesser
102 of the new and old sizes.
103 If the new size is larger, the value of the newly allocated portion
104 of the object is indeterminate and uninitialized.
105 If the space cannot be allocated, the object
116 and allocates a new object.
120 function causes the space pointed to by
122 to be placed on a list of free blocks to make it available for future
123 allocation by the application, but not returned to the kernel.
131 was previously freed by
133 or a reallocation function,
134 the behavior is undefined and the double free is a security concern.
136 Designed for safe allocation of arrays,
139 function is similar to
141 except it operates on
145 and checks for integer overflow in the calculation
150 Used for the allocation of memory holding sensitive data,
155 functions guarantee that memory becoming unallocated is explicitly
157 meaning cached free objects are cleared with
158 .Xr explicit_bzero 3 .
162 function is similar to
164 except it ensures newly allocated memory is cleared similar to
171 is ignored and the call is equivalent to
178 must be a value such that
182 is the size of the earlier allocation that returned
184 otherwise the behaviour is undefined.
188 function is similar to the
190 function except it ensures memory is explicitly discarded.
202 argument must be equal or smaller than the size of the earlier allocation
206 guarantees the memory range starting at
210 is discarded while deallocating the whole object originally allocated.
212 Upon successful completion, the allocation functions
213 return a pointer to the allocated space; otherwise,
224 results in integer overflow,
244 results in integer overflow
259 when there is multiplication in the
265 For example, avoid this common idiom as it may lead to integer overflow:
266 .Bd -literal -offset indent
267 if ((p = malloc(num * size)) == NULL)
271 A drop-in replacement is the
275 .Bd -literal -offset indent
276 if ((p = reallocarray(NULL, num, size)) == NULL)
282 may be used at the cost of initialization overhead.
286 be careful to avoid the following idiom:
287 .Bd -literal -offset indent
289 if ((p = realloc(p, size)) == NULL)
293 Do not adjust the variable describing how much memory has been allocated
294 until the allocation has been successful.
295 This can cause aberrant program behavior if the incorrect size value is used.
296 In most cases, the above sample will also result in a leak of memory.
297 As stated earlier, a return value of
299 indicates that the old object still remains allocated.
300 Better code looks like this:
301 .Bd -literal -offset indent
303 if ((newp = realloc(p, newsize)) == NULL) {
315 it is important to ensure the new size value will not overflow;
316 i.e. avoid allocations like the following:
317 .Bd -literal -offset indent
318 if ((newp = realloc(p, num * size)) == NULL) {
324 .Bd -literal -offset indent
325 if ((newp = reallocarray(p, num, size)) == NULL) {
334 is equivalent to calling
336 Instead of this idiom:
337 .Bd -literal -offset indent
339 newp = malloc(newsize);
341 newp = realloc(p, newsize);
345 .Bd -literal -offset indent
346 newp = realloc(p, newsize);
351 function should be used for resizing objects containing sensitive data like
353 To avoid leaking information,
354 it guarantees memory is cleared before placing it on the internal free list.
355 Deallocation of such an object should be done by calling
360 must be used with multiplication, be sure to test for overflow:
361 .Bd -literal -offset indent
365 /* Check for size_t overflow */
366 if (size && num > SIZE_MAX / size)
367 errc(1, EOVERFLOW, "overflow");
369 if ((p = malloc(num * size)) == NULL)
373 The above test is not sufficient in all cases.
374 For example, multiplying ints requires a different set of checks:
375 .Bd -literal -offset indent
379 /* Avoid invalid requests */
380 if (size < 0 || num < 0)
381 errc(1, EOVERFLOW, "overflow");
383 /* Check for signed int overflow */
384 if (size && num > INT_MAX / size)
385 errc(1, EOVERFLOW, "overflow");
387 if ((p = malloc(num * size)) == NULL)
391 Assuming the implementation checks for integer overflow as
393 does, it is much easier to use
399 The above examples could be simplified to:
400 .Bd -literal -offset indent
401 if ((p = reallocarray(NULL, num, size)) == NULL)
405 or at the cost of initialization:
406 .Bd -literal -offset indent
407 if ((p = calloc(num, size)) == NULL)
416 .Xr posix_memalign 3 ,
432 are 0, the return value is implementation defined;
433 other conforming implementations may return
439 internal kernel function and a predecessor to
458 A new implementation by Chris Kingsley was introduced in
460 followed by a complete rewrite by Poul-Henning Kamp which appeared in
464 These implementations were all
469 Thierry Deval rewrote
474 making the page addresses returned by
477 A rewrite by Otto Moerbeek introducing a new central data structure and more
478 randomization appeared in
496 be wary of signed integer and
498 overflow especially when there is multiplication in the
502 Signed integer overflow will cause undefined behavior which compilers
503 typically handle by wrapping back around to negative numbers.
504 Depending on the input, this can result in allocating more or less
505 memory than intended.
507 An unsigned overflow has defined behavior which will wrap back around and
508 return less memory than intended.
510 A signed or unsigned integer overflow is a
512 risk if less memory is returned than intended.
513 Subsequent code may corrupt the heap by writing beyond the memory that was
515 An attacker may be able to leverage this heap corruption to execute arbitrary
523 instead of using multiplication in
527 to avoid these problems.
529 The default memory allocator in libc is not scalable. Concurrent accesses by
530 multiple threads are single-threaded through the use of a single lock.
531 Multithreaded applications that make heavy use of dynamic memory allocation
532 should be linked either
536 for the time being (until the default allocator is replaced). See
537 .Xr umem_alloc 3malloc .