dev: suppress set but not used warnings
[unleashed.git] / lib / libc / malloc.3
blob00684ed9371ec72ae00b2dfe3b896daadd79ebaa
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.115 2017/05/15 18:05:34 tb Exp $
34 .\"
35 .Dd $Mdocdate: November 13 2017 $
36 .Dt MALLOC 3
37 .Os
38 .Sh NAME
39 .Nm malloc ,
40 .Nm calloc ,
41 .Nm realloc ,
42 .Nm free ,
43 .Nm reallocarray ,
44 .Nm recallocarray ,
45 .Nm freezero
46 .Nd memory allocation and deallocation
47 .Sh SYNOPSIS
48 .In stdlib.h
49 .Ft void *
50 .Fn malloc "size_t size"
51 .Ft void *
52 .Fn calloc "size_t nmemb" "size_t size"
53 .Ft void *
54 .Fn realloc "void *ptr" "size_t size"
55 .Ft void
56 .Fn free "void *ptr"
57 .Ft void *
58 .Fn reallocarray "void *ptr" "size_t nmemb" "size_t size"
59 .Ft void *
60 .Fn recallocarray "void *ptr" "size_t oldnmemb" "size_t nmemb" "size_t size"
61 .Ft void
62 .Fn freezero "void *ptr" "size_t size"
63 .Sh DESCRIPTION
64 The standard functions
65 .Fn malloc ,
66 .Fn calloc ,
67 and
68 .Fn realloc
69 allocate
70 .Em objects ,
71 regions of memory to store values.
72 The
73 .Fn malloc
74 function allocates uninitialized space for an object of
75 the specified
76 .Fa size .
77 The allocated space is suitably aligned (after possible pointer coercion) for
78 storage of any type of object.
79 .Pp
80 The
81 .Fn calloc
82 function allocates space for an array of
83 .Fa nmemb
84 objects, each of the specified
85 .Fa size .
86 The space is initialized to zero.
87 .Pp
88 The
89 .Fn realloc
90 function changes the size of the object pointed to by
91 .Fa ptr
93 .Fa size
94 bytes and returns a pointer to the (possibly moved) object.
96 .Fa ptr
97 is not
98 .Dv NULL ,
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
106 pointed to by
107 .Fa ptr
108 is unchanged.
110 .Fa ptr
112 .Dv NULL ,
113 .Fn realloc
114 behaves like
115 .Fn malloc
116 and allocates a new object.
119 .Fn free
120 function causes the space pointed to by
121 .Fa ptr
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.
125 .Fa ptr
127 .Dv NULL ,
128 no action occurs.
130 .Fa ptr
131 was previously freed by
132 .Fn free
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,
138 .Fn reallocarray
139 function is similar to
140 .Fn realloc
141 except it operates on
142 .Fa nmemb
143 members of size
144 .Fa size
145 and checks for integer overflow in the calculation
146 .Fa nmemb
148 .Fa size .
150 Used for the allocation of memory holding sensitive data,
152 .Fn recallocarray
154 .Fn freezero
155 functions guarantee that memory becoming unallocated is explicitly
156 .Em discarded ,
157 meaning cached free objects are cleared with
158 .Xr explicit_bzero 3 .
161 .Fn recallocarray
162 function is similar to
163 .Fn reallocarray
164 except it ensures newly allocated memory is cleared similar to
165 .Fn calloc .
167 .Fa ptr
169 .Dv NULL ,
170 .Fa oldnmemb
171 is ignored and the call is equivalent to
172 .Fn calloc .
174 .Fa ptr
175 is not
176 .Dv NULL ,
177 .Fa oldnmemb
178 must be a value such that
179 .Fa oldnmemb
181 .Fa size
182 is the size of the earlier allocation that returned
183 .Fa ptr ,
184 otherwise the behaviour is undefined.
187 .Fn freezero
188 function is similar to the
189 .Fn free
190 function except it ensures memory is explicitly discarded.
192 .Fa ptr
194 .Dv NULL ,
195 no action occurs.
197 .Fa ptr
198 is not
199 .Dv NULL ,
201 .Fa size
202 argument must be equal or smaller than the size of the earlier allocation
203 that returned
204 .Fa ptr .
205 .Fn freezero
206 guarantees the memory range starting at
207 .Fa ptr
208 with length
209 .Fa size
210 is discarded while deallocating the whole object originally allocated.
211 .Sh RETURN VALUES
212 Upon successful completion, the allocation functions
213 return a pointer to the allocated space; otherwise,
214 .Dv NULL
215 is returned and
216 .Va errno
217 is set to
218 .Er ENOMEM .
220 If multiplying
221 .Fa nmemb
223 .Fa size
224 results in integer overflow,
225 .Fn calloc ,
226 .Fn reallocarray
228 .Fn recallocarray
229 return
230 .Dv NULL
231 and set
232 .Va errno
234 .Er ENOMEM .
237 .Fa ptr
238 is not
239 .Dv NULL
240 and multiplying
241 .Fa oldnmemb
243 .Fa size
244 results in integer overflow
245 .Fn recallocarray
246 returns
247 .Dv NULL
248 and sets
249 .Va errno
251 .Er EINVAL .
252 .Sh IDIOMS
253 Consider
254 .Fn calloc
255 or the extensions
256 .Fn reallocarray
258 .Fn recallocarray
259 when there is multiplication in the
260 .Fa size
261 argument of
262 .Fn malloc
264 .Fn realloc .
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)
268         err(1, NULL);
271 A drop-in replacement is the
273 extension
274 .Fn reallocarray :
275 .Bd -literal -offset indent
276 if ((p = reallocarray(NULL, num, size)) == NULL)
277         err(1, NULL);
280 Alternatively,
281 .Fn calloc
282 may be used at the cost of initialization overhead.
284 When using
285 .Fn realloc ,
286 be careful to avoid the following idiom:
287 .Bd -literal -offset indent
288 size += 50;
289 if ((p = realloc(p, size)) == NULL)
290         return (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
298 .Dv NULL
299 indicates that the old object still remains allocated.
300 Better code looks like this:
301 .Bd -literal -offset indent
302 newsize = size + 50;
303 if ((newp = realloc(p, newsize)) == NULL) {
304         free(p);
305         p = NULL;
306         size = 0;
307         return (NULL);
309 p = newp;
310 size = newsize;
313 As with
314 .Fn malloc ,
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) {
319         ...
322 Instead, use
323 .Fn reallocarray :
324 .Bd -literal -offset indent
325 if ((newp = reallocarray(p, num, size)) == NULL) {
326         ...
329 Calling
330 .Fn realloc
331 with a
332 .Dv NULL
333 .Fa ptr
334 is equivalent to calling
335 .Fn malloc .
336 Instead of this idiom:
337 .Bd -literal -offset indent
338 if (p == NULL)
339         newp = malloc(newsize);
340 else
341         newp = realloc(p, newsize);
344 Use the following:
345 .Bd -literal -offset indent
346 newp = realloc(p, newsize);
350 .Fn recallocarray
351 function should be used for resizing objects containing sensitive data like
352 keys.
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
356 .Fn freezero .
357 .Sh EXAMPLES
359 .Fn malloc
360 must be used with multiplication, be sure to test for overflow:
361 .Bd -literal -offset indent
362 size_t num, size;
363 \&...
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)
370         err(1, 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
376 int num, size;
377 \&...
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)
388         err(1, NULL);
391 Assuming the implementation checks for integer overflow as
393 does, it is much easier to use
394 .Fn calloc ,
395 .Fn reallocarray ,
397 .Fn recallocarray .
399 The above examples could be simplified to:
400 .Bd -literal -offset indent
401 if ((p = reallocarray(NULL, num, size)) == NULL)
402         err(1, NULL);
405 or at the cost of initialization:
406 .Bd -literal -offset indent
407 if ((p = calloc(num, size)) == NULL)
408         err(1, NULL);
410 .Sh SEE ALSO
411 .Xr brk 2 ,
412 .Xr mmap 2 ,
413 .Xr munmap 2 ,
414 .Xr alloca 3 ,
415 .Xr getpagesize 3 ,
416 .Xr posix_memalign 3 ,
417 .Xr sysconf 3
418 .Sh STANDARDS
420 .Fn malloc ,
421 .Fn calloc ,
422 .Fn realloc ,
424 .Fn free
425 functions conform to
426 .St -ansiC .
429 .Fa nmemb
431 .Fa size
432 are 0, the return value is implementation defined;
433 other conforming implementations may return
434 .Dv NULL
435 in this case.
436 .Sh HISTORY
438 .Fn free
439 internal kernel function and a predecessor to
440 .Fn malloc ,
441 .Fn alloc ,
442 first appeared in
443 .At v1 .
444 C library functions
445 .Fn alloc
447 .Fn free
448 appeared in
449 .At v6 .
450 The functions
451 .Fn malloc ,
452 .Fn calloc ,
454 .Fn realloc
455 first appeared in
456 .At v7 .
458 A new implementation by Chris Kingsley was introduced in
459 .Bx 4.2 ,
460 followed by a complete rewrite by Poul-Henning Kamp which appeared in
461 .Fx 2.2
462 and was included in
463 .Ox 2.0 .
464 These implementations were all
465 .Xr sbrk 2
466 based.
468 .Ox 3.8 ,
469 Thierry Deval rewrote
471 to use the
472 .Xr mmap 2
473 system call,
474 making the page addresses returned by
476 random.
477 A rewrite by Otto Moerbeek introducing a new central data structure and more
478 randomization appeared in
479 .Ox 4.4 .
482 .Fn reallocarray
483 function appeared in
484 .Ox 5.6 .
486 .Fn recallocarray
487 function appeared in
488 .Ox 6.1 .
490 .Fn freezero
491 function appeared in
492 .Ox 6.2 .
493 .Sh CAVEATS
494 When using
495 .Fn malloc ,
496 be wary of signed integer and
497 .Vt size_t
498 overflow especially when there is multiplication in the
499 .Fa size
500 argument.
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
511 .Em security
512 risk if less memory is returned than intended.
513 Subsequent code may corrupt the heap by writing beyond the memory that was
514 allocated.
515 An attacker may be able to leverage this heap corruption to execute arbitrary
516 code.
518 Consider using
519 .Fn calloc ,
520 .Fn reallocarray
522 .Fn recallocarray
523 instead of using multiplication in
524 .Fn malloc
526 .Fn realloc
527 to avoid these problems.
528 .Sh BUGS
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
533 .Lb umem
535 .Lb mtmalloc
536 for the time being (until the default allocator is replaced). See
537 .Xr umem_alloc 3malloc .