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.109 2017/04/06 17:00:52 otto Exp $
35 .Dd $Mdocdate: April 6 2017 $
45 .Nd memory allocation and deallocation
49 .Fn malloc "size_t size"
51 .Fn calloc "size_t nmemb" "size_t size"
53 .Fn reallocarray "void *ptr" "size_t nmemb" "size_t size"
55 .Fn recallocarray "void *ptr" "size_t oldnmemb" "size_t nmemb" "size_t size"
57 .Fn realloc "void *ptr" "size_t size"
63 function allocates uninitialized space for an object of
66 The allocated space is suitably aligned (after possible pointer coercion) for
67 storage of any type of object.
71 function allocates space for an array of
73 objects, each of the specified
75 The space is initialized to zero.
79 function changes the size of the object pointed to by
83 bytes and returns a pointer to the (possibly moved) object.
84 The contents of the object are unchanged up to the lesser
85 of the new and old sizes.
86 If the new size is larger, the value of the newly allocated portion
87 of the object is indeterminate and uninitialized.
88 If the space cannot be allocated, the object
99 and allocates a new object.
103 function is similar to
105 except it operates on
109 and checks for integer overflow in the calculation
116 function is similar to
118 except it ensures newly allocated memory is cleared similar to
120 Memory that becomes unallocated while shrinking or moving existing
121 allocations is explicitly discarded (meaning, pages of memory
124 and smaller allocations are cleared with
125 .Xr explicit_bzero 3 ) .
132 is ignored and the call is equivalent to
140 must be a value such that
144 is the size of the earlier allocation that returned
146 otherwise the behaviour is undefined.
150 function causes the space pointed to by
152 to be placed on a list of free pages to make it available for future allocation
153 by the application, but not returned to the kernel.
158 pointer, no action occurs.
161 was previously freed by
163 or a reallocation function,
164 the behavior is undefined and the double free is a security concern.
166 Upon successful completion, the allocation functions
167 return a pointer to the allocated space; otherwise, a
169 pointer is returned and
178 results in integer overflow,
192 is not NULL and multiplying
196 results in integer overflow
211 when there is multiplication in the
217 For example, avoid this common idiom as it may lead to integer overflow:
218 .Bd -literal -offset indent
219 if ((p = malloc(num * size)) == NULL)
223 A drop-in replacement is the
227 .Bd -literal -offset indent
228 if ((p = reallocarray(NULL, num, size)) == NULL)
234 may be used at the cost of initialization overhead.
238 be careful to avoid the following idiom:
239 .Bd -literal -offset indent
241 if ((p = realloc(p, size)) == NULL)
245 Do not adjust the variable describing how much memory has been allocated
246 until the allocation has been successful.
247 This can cause aberrant program behavior if the incorrect size value is used.
248 In most cases, the above sample will also result in a leak of memory.
249 As stated earlier, a return value of
251 indicates that the old object still remains allocated.
252 Better code looks like this:
253 .Bd -literal -offset indent
255 if ((newp = realloc(p, newsize)) == NULL) {
267 it is important to ensure the new size value will not overflow;
268 i.e. avoid allocations like the following:
269 .Bd -literal -offset indent
270 if ((newp = realloc(p, num * size)) == NULL) {
276 .Bd -literal -offset indent
277 if ((newp = reallocarray(p, num, size)) == NULL) {
286 is equivalent to calling
288 Instead of this idiom:
289 .Bd -literal -offset indent
291 newp = malloc(newsize);
293 newp = realloc(p, newsize);
297 .Bd -literal -offset indent
298 newp = realloc(p, newsize);
303 function should be used for resizing objects containing sensitive data like
305 To avoid leaking information,
306 it guarantees memory is cleared before placing it on the internal free list.
309 call for such an object should still be preceded by a call to
310 .Xr explicit_bzero 3 .
314 must be used with multiplication, be sure to test for overflow:
315 .Bd -literal -offset indent
319 /* Check for size_t overflow */
320 if (size && num > SIZE_MAX / size)
321 errc(1, EOVERFLOW, "overflow");
323 if ((p = malloc(num * size)) == NULL)
327 The above test is not sufficient in all cases.
328 For example, multiplying ints requires a different set of checks:
329 .Bd -literal -offset indent
333 /* Avoid invalid requests */
334 if (size < 0 || num < 0)
335 errc(1, EOVERFLOW, "overflow");
337 /* Check for signed int overflow */
338 if (size && num > INT_MAX / size)
339 errc(1, EOVERFLOW, "overflow");
341 if ((p = malloc(num * size)) == NULL)
345 Assuming the implementation checks for integer overflow as
347 does, it is much easier to use
353 The above examples could be simplified to:
354 .Bd -literal -offset indent
355 if ((p = reallocarray(NULL, num, size)) == NULL)
359 or at the cost of initialization:
360 .Bd -literal -offset indent
361 if ((p = calloc(num, size)) == NULL)
370 .Xr posix_memalign 3 ,
386 are 0, the return value is implementation defined;
387 other conforming implementations may return
393 internal kernel function and a predecessor to
412 A new implementation by Chris Kingsley was introduced in
414 followed by a complete rewrite by Poul-Henning Kamp which appeared in
418 These implementations were all
423 Thierry Deval rewrote
428 making the page addresses returned by
431 A rewrite by Otto Moerbeek introducing a new central data structure and more
432 randomization appeared in
446 be wary of signed integer and
448 overflow especially when there is multiplication in the
452 Signed integer overflow will cause undefined behavior which compilers
453 typically handle by wrapping back around to negative numbers.
454 Depending on the input, this can result in allocating more or less
455 memory than intended.
457 An unsigned overflow has defined behavior which will wrap back around and
458 return less memory than intended.
460 A signed or unsigned integer overflow is a
462 risk if less memory is returned than intended.
463 Subsequent code may corrupt the heap by writing beyond the memory that was
465 An attacker may be able to leverage this heap corruption to execute arbitrary
473 instead of using multiplication in
477 to avoid these problems.
479 The default memory allocator in libc is not scalable. Concurrent accesses by
480 multiple threads are single-threaded through the use of a single lock.
481 Multithreaded applications that make heavy use of dynamic memory allocation
482 should be linked either
486 for the time being (until the default allocator is replaced). See
487 .Xr umem_alloc 3malloc .