libc: import recallocarray(3) from openbsd
[unleashed.git] / lib / libc / malloc.3
blob3778253910932d5ba7a618d29912dbf48a92021b
1 .\"
2 .\" Copyright (c) 1980, 1991, 1993
3 .\"     The Regents of the University of California.  All rights reserved.
4 .\"
5 .\" This code is derived from software contributed to Berkeley by
6 .\" the American National Standards Committee X3, on Information
7 .\" Processing Systems.
8 .\"
9 .\" Redistribution and use in source and binary forms, with or without
10 .\" modification, are permitted provided that the following conditions
11 .\" are met:
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.
20 .\"
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
31 .\" SUCH DAMAGE.
32 .\"
33 .\"     $OpenBSD: malloc.3,v 1.109 2017/04/06 17:00:52 otto Exp $
34 .\"
35 .Dd $Mdocdate: April 6 2017 $
36 .Dt MALLOC 3
37 .Os
38 .Sh NAME
39 .Nm malloc ,
40 .Nm calloc ,
41 .Nm reallocarray ,
42 .Nm recallocarray ,
43 .Nm realloc ,
44 .Nm free
45 .Nd memory allocation and deallocation
46 .Sh SYNOPSIS
47 .In stdlib.h
48 .Ft void *
49 .Fn malloc "size_t size"
50 .Ft void *
51 .Fn calloc "size_t nmemb" "size_t size"
52 .Ft void *
53 .Fn reallocarray "void *ptr" "size_t nmemb" "size_t size"
54 .Ft void *
55 .Fn recallocarray "void *ptr" "size_t oldnmemb" "size_t nmemb" "size_t size"
56 .Ft void *
57 .Fn realloc "void *ptr" "size_t size"
58 .Ft void
59 .Fn free "void *ptr"
60 .Sh DESCRIPTION
61 The
62 .Fn malloc
63 function allocates uninitialized space for an object of
64 the specified
65 .Fa size .
66 The allocated space is suitably aligned (after possible pointer coercion) for
67 storage of any type of object.
68 .Pp
69 The
70 .Fn calloc
71 function allocates space for an array of
72 .Fa nmemb
73 objects, each of the specified
74 .Fa size .
75 The space is initialized to zero.
76 .Pp
77 The
78 .Fn realloc
79 function changes the size of the object pointed to by
80 .Fa ptr
82 .Fa size
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
89 pointed to by
90 .Fa ptr
91 is unchanged.
93 .Fa ptr
95 .Dv NULL ,
96 .Fn realloc
97 behaves like
98 .Fn malloc
99 and allocates a new object.
102 .Fn reallocarray
103 function is similar to
104 .Fn realloc
105 except it operates on
106 .Fa nmemb
107 members of size
108 .Fa size
109 and checks for integer overflow in the calculation
110 .Fa nmemb
112 .Fa size .
115 .Fn recallocarray
116 function is similar to
117 .Fn reallocarray
118 except it ensures newly allocated memory is cleared similar to
119 .Xr calloc 3 .
120 Memory that becomes unallocated while shrinking or moving existing
121 allocations is explicitly discarded (meaning, pages of memory
122 are disposed via
123 .Xr munmap 2 ,
124 and smaller allocations are cleared with
125 .Xr explicit_bzero 3 ) .
127 .Fa ptr
128 is a
129 .Dv NULL
130 pointer,
131 .Fa oldnmemb
132 is ignored and the call is equivalent to
133 .Fn calloc .
135 .Fa ptr
136 is not a
137 .Dv NULL
138 pointer,
139 .Fa oldnmemb
140 must be a value such that
141 .Fa oldnmemb
143 .Fa size
144 is the size of the earlier allocation that returned
145 .Fa ptr ,
146 otherwise the behaviour is undefined.
149 .Fn free
150 function causes the space pointed to by
151 .Fa ptr
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.
155 .Fa ptr
156 is a
157 .Dv NULL
158 pointer, no action occurs.
160 .Fa ptr
161 was previously freed by
162 .Fn free
163 or a reallocation function,
164 the behavior is undefined and the double free is a security concern.
165 .Sh RETURN VALUES
166 Upon successful completion, the allocation functions
167 return a pointer to the allocated space; otherwise, a
168 .Dv NULL
169 pointer is returned and
170 .Va errno
171 is set to
172 .Er ENOMEM .
174 If multiplying
175 .Fa nmemb
177 .Fa size
178 results in integer overflow,
179 .Fn calloc ,
180 .Fn reallocarray
182 .Fn recallocarray
183 return
184 .Dv NULL
185 and set
186 .Va errno
188 .Er ENOMEM .
191 .Fa ptr
192 is not NULL and multiplying
193 .Fa oldnmemb
195 .Fa size
196 results in integer overflow
197 .Fn recallocarray
198 returns
199 .Dv NULL
200 and sets
201 .Va errno
203 .Er EINVAL .
204 .Sh IDIOMS
205 Consider
206 .Fn calloc
207 or the extensions
208 .Fn reallocarray
210 .Fn recallocarray
211 when there is multiplication in the
212 .Fa size
213 argument of
214 .Fn malloc
216 .Fn realloc .
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)
220         err(1, NULL);
223 A drop-in replacement is the
225 extension
226 .Fn reallocarray :
227 .Bd -literal -offset indent
228 if ((p = reallocarray(NULL, num, size)) == NULL)
229         err(1, NULL);
232 Alternatively,
233 .Fn calloc
234 may be used at the cost of initialization overhead.
236 When using
237 .Fn realloc ,
238 be careful to avoid the following idiom:
239 .Bd -literal -offset indent
240 size += 50;
241 if ((p = realloc(p, size)) == NULL)
242         return (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
250 .Dv NULL
251 indicates that the old object still remains allocated.
252 Better code looks like this:
253 .Bd -literal -offset indent
254 newsize = size + 50;
255 if ((newp = realloc(p, newsize)) == NULL) {
256         free(p);
257         p = NULL;
258         size = 0;
259         return (NULL);
261 p = newp;
262 size = newsize;
265 As with
266 .Fn malloc ,
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) {
271         ...
274 Instead, use
275 .Fn reallocarray :
276 .Bd -literal -offset indent
277 if ((newp = reallocarray(p, num, size)) == NULL) {
278         ...
281 Calling
282 .Fn realloc
283 with a
284 .Dv NULL
285 .Fa ptr
286 is equivalent to calling
287 .Fn malloc .
288 Instead of this idiom:
289 .Bd -literal -offset indent
290 if (p == NULL)
291         newp = malloc(newsize);
292 else
293         newp = realloc(p, newsize);
296 Use the following:
297 .Bd -literal -offset indent
298 newp = realloc(p, newsize);
302 .Fn recallocarray
303 function should be used for resizing objects containing sensitive data like
304 keys.
305 To avoid leaking information,
306 it guarantees memory is cleared before placing it on the internal free list.
308 .Fn free
309 call for such an object should still be preceded by a call to
310 .Xr explicit_bzero 3 .
311 .Sh EXAMPLES
313 .Fn malloc
314 must be used with multiplication, be sure to test for overflow:
315 .Bd -literal -offset indent
316 size_t num, size;
317 \&...
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)
324         err(1, 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
330 int num, size;
331 \&...
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)
342         err(1, NULL);
345 Assuming the implementation checks for integer overflow as
347 does, it is much easier to use
348 .Fn calloc ,
349 .Fn reallocarray ,
351 .Fn recallocarray .
353 The above examples could be simplified to:
354 .Bd -literal -offset indent
355 if ((p = reallocarray(NULL, num, size)) == NULL)
356         err(1, NULL);
359 or at the cost of initialization:
360 .Bd -literal -offset indent
361 if ((p = calloc(num, size)) == NULL)
362         err(1, NULL);
364 .Sh SEE ALSO
365 .Xr brk 2 ,
366 .Xr mmap 2 ,
367 .Xr munmap 2 ,
368 .Xr alloca 3 ,
369 .Xr getpagesize 3 ,
370 .Xr posix_memalign 3 ,
371 .Xr sysconf 3
372 .Sh STANDARDS
374 .Fn malloc ,
375 .Fn calloc ,
376 .Fn realloc ,
378 .Fn free
379 functions conform to
380 .St -ansiC .
383 .Fa nmemb
385 .Fa size
386 are 0, the return value is implementation defined;
387 other conforming implementations may return
388 .Dv NULL
389 in this case.
390 .Sh HISTORY
392 .Fn free
393 internal kernel function and a predecessor to
394 .Fn malloc ,
395 .Fn alloc ,
396 first appeared in
397 .At v1 .
398 C library functions
399 .Fn alloc
401 .Fn free
402 appeared in
403 .At v6 .
404 The functions
405 .Fn malloc ,
406 .Fn calloc ,
408 .Fn realloc
409 first appeared in
410 .At v7 .
412 A new implementation by Chris Kingsley was introduced in
413 .Bx 4.2 ,
414 followed by a complete rewrite by Poul-Henning Kamp which appeared in
415 .Fx 2.2
416 and was included in
417 .Ox 2.0 .
418 These implementations were all
419 .Xr sbrk 2
420 based.
422 .Ox 3.8 ,
423 Thierry Deval rewrote
425 to use the
426 .Xr mmap 2
427 system call,
428 making the page addresses returned by
430 random.
431 A rewrite by Otto Moerbeek introducing a new central data structure and more
432 randomization appeared in
433 .Ox 4.4 .
436 .Fn reallocarray
437 function appeared in
438 .Ox 5.6 .
440 .Fn recallocarray
441 function appeared in
442 .Ox 6.1 .
443 .Sh CAVEATS
444 When using
445 .Fn malloc ,
446 be wary of signed integer and
447 .Vt size_t
448 overflow especially when there is multiplication in the
449 .Fa size
450 argument.
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
461 .Em security
462 risk if less memory is returned than intended.
463 Subsequent code may corrupt the heap by writing beyond the memory that was
464 allocated.
465 An attacker may be able to leverage this heap corruption to execute arbitrary
466 code.
468 Consider using
469 .Fn calloc ,
470 .Fn reallocarray
472 .Fn recallocarray
473 instead of using multiplication in
474 .Fn malloc
476 .Fn realloc
477 to avoid these problems.
478 .Sh BUGS
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
483 .Lb umem
485 .Lb mtmalloc
486 for the time being (until the default allocator is replaced). See
487 .Xr umem_alloc 3malloc .