xref: /openbsd-src/lib/libc/stdlib/malloc.3 (revision c90a81c56dcebd6a1b73fe4aff9b03385b8e63b3)
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.122 2018/12/05 17:11:59 schwarze Exp $
34.\"
35.Dd $Mdocdate: December 5 2018 $
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.Nm aligned_alloc
47.Nd memory allocation and deallocation
48.Sh SYNOPSIS
49.In stdlib.h
50.Ft void *
51.Fn malloc "size_t size"
52.Ft void *
53.Fn calloc "size_t nmemb" "size_t size"
54.Ft void *
55.Fn realloc "void *ptr" "size_t size"
56.Ft void
57.Fn free "void *ptr"
58.Ft void *
59.Fn reallocarray "void *ptr" "size_t nmemb" "size_t size"
60.Ft void *
61.Fn recallocarray "void *ptr" "size_t oldnmemb" "size_t nmemb" "size_t size"
62.Ft void
63.Fn freezero "void *ptr" "size_t size"
64.Ft void *
65.Fn aligned_alloc "size_t alignment" "size_t size"
66.Vt char *malloc_options ;
67.Sh DESCRIPTION
68The standard functions
69.Fn malloc ,
70.Fn calloc ,
71and
72.Fn realloc
73allocate
74.Em objects ,
75regions of memory to store values.
76The
77.Fn malloc
78function allocates uninitialized space for an object of
79the specified
80.Fa size .
81.Fn malloc
82maintains multiple lists of free objects according to size, allocating
83from the appropriate list or requesting memory from the kernel.
84The allocated space is suitably aligned (after possible pointer coercion) for
85storage of any type of object.
86.Pp
87The
88.Fn calloc
89function allocates space for an array of
90.Fa nmemb
91objects, each of the specified
92.Fa size .
93The space is initialized to zero.
94.Pp
95The
96.Fn realloc
97function changes the size of the object pointed to by
98.Fa ptr
99to
100.Fa size
101bytes and returns a pointer to the (possibly moved) object.
102If
103.Fa ptr
104is not
105.Dv NULL ,
106it must be a pointer returned by an earlier call to an allocation or
107reallocation function that was not freed in between.
108The contents of the object are unchanged up to the lesser
109of the new and old sizes.
110If the new size is larger, the value of the newly allocated portion
111of the object is indeterminate and uninitialized.
112If the space cannot be allocated, the object
113pointed to by
114.Fa ptr
115is unchanged.
116If
117.Fa ptr
118is
119.Dv NULL ,
120.Fn realloc
121behaves like
122.Fn malloc
123and allocates a new object.
124.Pp
125The
126.Fn free
127function causes the space pointed to by
128.Fa ptr
129to be either placed on a list of free blocks to make it available for future
130allocation or, when appropriate, to be returned to the kernel using
131.Xr munmap 2 .
132If
133.Fa ptr
134is
135.Dv NULL ,
136no action occurs.
137If
138.Fa ptr
139was previously freed by
140.Fn free
141or a reallocation function,
142the behavior is undefined and the double free is a security concern.
143.Pp
144Designed for safe allocation of arrays,
145the
146.Fn reallocarray
147function is similar to
148.Fn realloc
149except it operates on
150.Fa nmemb
151members of size
152.Fa size
153and checks for integer overflow in the calculation
154.Fa nmemb
155*
156.Fa size .
157.Pp
158Used for the allocation of memory holding sensitive data,
159the
160.Fn recallocarray
161and
162.Fn freezero
163functions guarantee that memory becoming unallocated is explicitly
164.Em discarded ,
165meaning pages of memory are disposed via
166.Xr munmap 2
167and cached free objects are cleared with
168.Xr explicit_bzero 3 .
169.Pp
170The
171.Fn recallocarray
172function is similar to
173.Fn reallocarray
174except it ensures newly allocated memory is cleared similar to
175.Fn calloc .
176If
177.Fa ptr
178is
179.Dv NULL ,
180.Fa oldnmemb
181is ignored and the call is equivalent to
182.Fn calloc .
183If
184.Fa ptr
185is not
186.Dv NULL ,
187.Fa oldnmemb
188must be a value such that
189.Fa oldnmemb
190*
191.Fa size
192is the size of the earlier allocation that returned
193.Fa ptr ,
194otherwise the behavior is undefined.
195.Pp
196The
197.Fn freezero
198function is similar to the
199.Fn free
200function except it ensures memory is explicitly discarded.
201If
202.Fa ptr
203is
204.Dv NULL ,
205no action occurs.
206If
207.Fa ptr
208is not
209.Dv NULL ,
210the
211.Fa size
212argument must be equal to or smaller than the size of the earlier allocation
213that returned
214.Fa ptr .
215.Fn freezero
216guarantees the memory range starting at
217.Fa ptr
218with length
219.Fa size
220is discarded while deallocating the whole object originally allocated.
221.Pp
222The
223.Fn aligned_alloc
224function allocates
225.Fa size
226bytes of memory such that the allocation's base address is a multiple of
227.Fa alignment .
228The requested
229.Fa alignment
230must be a power of 2.
231If
232.Fa size
233is not a multiple of
234.Fa alignment ,
235behavior is undefined.
236.Sh MALLOC OPTIONS
237Upon the first call to the
238.Fn malloc
239family of functions, an initialization sequence inspects the
240value of the
241.Va vm.malloc_conf
242.Xr sysctl 2 ,
243next checks the environment for a variable called
244.Ev MALLOC_OPTIONS ,
245and finally looks at the global variable
246.Va malloc_options
247in the program.
248Each is scanned for the flags documented below.
249Unless otherwise noted uppercase means on, lowercase means off.
250.Bl -tag -width indent
251.It Cm C
252.Dq Canaries .
253Add canaries at the end of allocations in order to detect
254heap overflows.
255The canary's content is checked when
256.Nm free
257is called.
258If it has been corrupted, the process is aborted.
259.It Cm D
260.Dq Dump .
261.Fn malloc
262will dump statistics to the file
263.Pa ./malloc.out ,
264if it already exists,
265at exit.
266This option requires the library to have been compiled with -DMALLOC_STATS in
267order to have any effect.
268.It Cm F
269.Dq Freecheck .
270Enable more extensive double free and use after free detection.
271All chunks in the delayed free list will be checked for double frees.
272Unused pages on the freelist are read and write protected to
273cause a segmentation fault upon access.
274.It Cm G
275.Dq Guard .
276Enable guard pages.
277Each page size or larger allocation is followed by a guard page that will
278cause a segmentation fault upon any access.
279.It Cm J
280.Dq More junking .
281Increase the junk level by one if it is smaller than 2.
282.It Cm j
283.Dq Less junking .
284Decrease the junk level by one if it is larger than 0.
285Junking writes some junk bytes into the area allocated.
286Junk is bytes of 0xdb when allocating;
287freed chunks are filled with 0xdf.
288By default the junk level is 1: after free,
289small chunks are completely junked;
290for pages the first part is junked.
291After a delay,
292the filling pattern is validated and the process is aborted if the pattern
293was modified.
294For junk level 2, junking is done on allocation as well and without size
295restrictions.
296If the junk level is zero, no junking is performed.
297.It Cm R
298.Dq realloc .
299Always reallocate when
300.Fn realloc
301is called, even if the initial allocation was big enough.
302.\".Pp
303.\".It Cm U
304.\".Dq utrace .
305.\"Generate entries for
306.\".Xr ktrace 1
307.\"for all operations.
308.\"Consult the source for this one.
309.It Cm S
310Enable all options suitable for security auditing.
311.It Cm U
312.Dq Free unmap .
313Enable use after free protection for larger allocations.
314Unused pages on the freelist are read and write protected to
315cause a segmentation fault upon access.
316.It Cm X
317.Dq xmalloc .
318Rather than return failure,
319.Xr abort 3
320the program with a diagnostic message on stderr.
321It is the intention that this option be set at compile time by
322including in the source:
323.Bd -literal -offset indent
324extern char *malloc_options;
325malloc_options = "X";
326.Ed
327.Pp
328Note that this will cause code that is supposed to handle
329out-of-memory conditions gracefully to abort instead.
330.It Cm <
331.Dq Halve the cache size .
332Decrease the size of the free page cache by a factor of two.
333.It Cm >
334.Dq Double the cache size .
335Increase the size of the free page cache by a factor of two.
336.El
337.Pp
338If a program changes behavior if any of these options (except
339.Cm X )
340are used,
341it is buggy.
342.Pp
343The default number of free pages cached is 64 per malloc pool.
344Multi-threaded programs use multiple pools.
345.Sh RETURN VALUES
346Upon successful completion, the allocation functions
347return a pointer to the allocated space; otherwise,
348.Dv NULL
349is returned and
350.Va errno
351is set to
352.Er ENOMEM .
353The function
354.Fn aligned_alloc
355returns
356.Dv NULL
357and sets
358.Va errno
359to
360.Er EINVAL
361if
362.Fa alignment
363is not a power of 2.
364.Pp
365If
366.Fa nmemb
367or
368.Fa size
369is equal to 0, a unique pointer to an access protected,
370zero sized object is returned.
371Access via this pointer will generate a
372.Dv SIGSEGV
373exception.
374.Pp
375If multiplying
376.Fa nmemb
377and
378.Fa size
379results in integer overflow,
380.Fn calloc ,
381.Fn reallocarray
382and
383.Fn recallocarray
384return
385.Dv NULL
386and set
387.Va errno
388to
389.Er ENOMEM .
390.Pp
391If
392.Fa ptr
393is not
394.Dv NULL
395and multiplying
396.Fa oldnmemb
397and
398.Fa size
399results in integer overflow
400.Fn recallocarray
401returns
402.Dv NULL
403and sets
404.Va errno
405to
406.Er EINVAL .
407.Sh IDIOMS
408Consider
409.Fn calloc
410or the extensions
411.Fn reallocarray
412and
413.Fn recallocarray
414when there is multiplication in the
415.Fa size
416argument of
417.Fn malloc
418or
419.Fn realloc .
420For example, avoid this common idiom as it may lead to integer overflow:
421.Bd -literal -offset indent
422if ((p = malloc(num * size)) == NULL)
423	err(1, NULL);
424.Ed
425.Pp
426A drop-in replacement is the
427.Ox
428extension
429.Fn reallocarray :
430.Bd -literal -offset indent
431if ((p = reallocarray(NULL, num, size)) == NULL)
432	err(1, NULL);
433.Ed
434.Pp
435Alternatively,
436.Fn calloc
437may be used at the cost of initialization overhead.
438.Pp
439When using
440.Fn realloc ,
441be careful to avoid the following idiom:
442.Bd -literal -offset indent
443size += 50;
444if ((p = realloc(p, size)) == NULL)
445	return (NULL);
446.Ed
447.Pp
448Do not adjust the variable describing how much memory has been allocated
449until the allocation has been successful.
450This can cause aberrant program behavior if the incorrect size value is used.
451In most cases, the above sample will also result in a leak of memory.
452As stated earlier, a return value of
453.Dv NULL
454indicates that the old object still remains allocated.
455Better code looks like this:
456.Bd -literal -offset indent
457newsize = size + 50;
458if ((newp = realloc(p, newsize)) == NULL) {
459	free(p);
460	p = NULL;
461	size = 0;
462	return (NULL);
463}
464p = newp;
465size = newsize;
466.Ed
467.Pp
468As with
469.Fn malloc ,
470it is important to ensure the new size value will not overflow;
471i.e. avoid allocations like the following:
472.Bd -literal -offset indent
473if ((newp = realloc(p, num * size)) == NULL) {
474	...
475.Ed
476.Pp
477Instead, use
478.Fn reallocarray :
479.Bd -literal -offset indent
480if ((newp = reallocarray(p, num, size)) == NULL) {
481	...
482.Ed
483.Pp
484Calling
485.Fn realloc
486with a
487.Dv NULL
488.Fa ptr
489is equivalent to calling
490.Fn malloc .
491Instead of this idiom:
492.Bd -literal -offset indent
493if (p == NULL)
494	newp = malloc(newsize);
495else
496	newp = realloc(p, newsize);
497.Ed
498.Pp
499Use the following:
500.Bd -literal -offset indent
501newp = realloc(p, newsize);
502.Ed
503.Pp
504The
505.Fn recallocarray
506function should be used for resizing objects containing sensitive data like
507keys.
508To avoid leaking information,
509it guarantees memory is cleared before placing it on the internal free list.
510Deallocation of such an object should be done by calling
511.Fn freezero .
512.Sh ENVIRONMENT
513.Bl -tag -width "MALLOC_OPTIONS"
514.It Ev MALLOC_OPTIONS
515String of option flags.
516.El
517.Sh EXAMPLES
518If
519.Fn malloc
520must be used with multiplication, be sure to test for overflow:
521.Bd -literal -offset indent
522size_t num, size;
523\&...
524
525/* Check for size_t overflow */
526if (size && num > SIZE_MAX / size)
527	errc(1, EOVERFLOW, "overflow");
528
529if ((p = malloc(num * size)) == NULL)
530	err(1, NULL);
531.Ed
532.Pp
533The above test is not sufficient in all cases.
534For example, multiplying ints requires a different set of checks:
535.Bd -literal -offset indent
536int num, size;
537\&...
538
539/* Avoid invalid requests */
540if (size < 0 || num < 0)
541	errc(1, EOVERFLOW, "overflow");
542
543/* Check for signed int overflow */
544if (size && num > INT_MAX / size)
545	errc(1, EOVERFLOW, "overflow");
546
547if ((p = malloc(num * size)) == NULL)
548	err(1, NULL);
549.Ed
550.Pp
551Assuming the implementation checks for integer overflow as
552.Ox
553does, it is much easier to use
554.Fn calloc ,
555.Fn reallocarray ,
556or
557.Fn recallocarray .
558.Pp
559The above examples could be simplified to:
560.Bd -literal -offset indent
561if ((p = reallocarray(NULL, num, size)) == NULL)
562	err(1, NULL);
563.Ed
564.Pp
565or at the cost of initialization:
566.Bd -literal -offset indent
567if ((p = calloc(num, size)) == NULL)
568	err(1, NULL);
569.Ed
570.Pp
571Set a systemwide reduction of the cache to a quarter of the
572default size and use guard pages:
573.Pp
574.Dl # sysctl vm.malloc_conf='G<<'
575.Sh DIAGNOSTICS
576If any of the functions detect an error condition,
577a message will be printed to file descriptor
5782 (not using stdio).
579Errors will result in the process being aborted.
580.Pp
581Here is a brief description of the error messages and what they mean:
582.Bl -tag -width Ds
583.It Dq out of memory
584If the
585.Cm X
586option is specified it is an error for the allocation functions
587to return
588.Dv NULL .
589.It Dq bogus pointer (double free?)
590An attempt to
591.Fn free
592or
593reallocate an unallocated pointer was made.
594.It Dq chunk is already free
595There was an attempt to free a chunk that had already been freed.
596.It Dq use after free
597A chunk has been modified after it was freed.
598.It Dq modified chunk-pointer
599The pointer passed to
600.Fn free
601or a reallocation function has been modified.
602.It Dq chunk canary corrupted address offset@length
603A byte after the requested size has been overwritten,
604indicating a heap overflow.
605The offset at which corruption was detected is printed before the @,
606and the requested length of the allocation after the @.
607.It Dq recorded old size oldsize != size
608.Fn recallocarray
609has detected that the given old size does not equal the recorded size in its
610meta data.
611Enabling option
612.Cm C
613allows
614.Fn recallocarray
615to catch more of these cases.
616.It Dq recursive call
617An attempt was made to call recursively into these functions, i.e., from a
618signal handler.
619This behavior is not supported.
620In particular, signal handlers should
621.Em not
622use any of the
623.Fn malloc
624functions nor utilize any other functions which may call
625.Fn malloc
626(e.g.,
627.Xr stdio 3
628routines).
629.It Dq unknown char in MALLOC_OPTIONS
630We found something we didn't understand.
631.It any other error
632.Fn malloc
633detected an internal error;
634consult sources and/or wizards.
635.El
636.Sh SEE ALSO
637.Xr brk 2 ,
638.Xr mmap 2 ,
639.Xr munmap 2 ,
640.Xr sysctl 2 ,
641.Xr alloca 3 ,
642.Xr getpagesize 3 ,
643.Xr posix_memalign 3
644.Sh STANDARDS
645The
646.Fn malloc ,
647.Fn calloc ,
648.Fn realloc ,
649and
650.Fn free
651functions conform to
652.St -ansiC .
653The
654.Fn aligned_alloc
655function conforms to
656.St -isoC-2011 .
657.Pp
658If
659.Fa nmemb
660or
661.Fa size
662are 0, the return value is implementation defined;
663other conforming implementations may return
664.Dv NULL
665in this case.
666.Pp
667The
668.Ev MALLOC_OPTIONS
669environment variable, the
670.Va vm.malloc_conf
671sysctl and the
672.Sx DIAGNOSTICS
673output are extensions to the standard.
674.Sh HISTORY
675A
676.Fn free
677internal kernel function and a predecessor to
678.Fn malloc ,
679.Fn alloc ,
680first appeared in
681.At v1 .
682C library functions
683.Fn alloc
684and
685.Fn free
686appeared in
687.At v6 .
688The functions
689.Fn malloc ,
690.Fn calloc ,
691and
692.Fn realloc
693first appeared in
694.At v7 .
695.Pp
696A new implementation by Chris Kingsley was introduced in
697.Bx 4.2 ,
698followed by a complete rewrite by Poul-Henning Kamp which appeared in
699.Fx 2.2
700and was included in
701.Ox 2.0 .
702These implementations were all
703.Xr sbrk 2
704based.
705In
706.Ox 3.8 ,
707Thierry Deval rewrote
708.Nm
709to use the
710.Xr mmap 2
711system call,
712making the page addresses returned by
713.Nm
714random.
715A rewrite by Otto Moerbeek introducing a new central data structure and more
716randomization appeared in
717.Ox 4.4 .
718.Pp
719The
720.Fn reallocarray
721function appeared in
722.Ox 5.6 .
723The
724.Fn recallocarray
725function appeared in
726.Ox 6.1 .
727The
728.Fn freezero
729function appeared in
730.Ox 6.2 .
731The
732.Fn aligned_alloc
733function appeared in
734.Ox 6.5 .
735.Sh CAVEATS
736When using
737.Fn malloc ,
738be wary of signed integer and
739.Vt size_t
740overflow especially when there is multiplication in the
741.Fa size
742argument.
743.Pp
744Signed integer overflow will cause undefined behavior which compilers
745typically handle by wrapping back around to negative numbers.
746Depending on the input, this can result in allocating more or less
747memory than intended.
748.Pp
749An unsigned overflow has defined behavior which will wrap back around and
750return less memory than intended.
751.Pp
752A signed or unsigned integer overflow is a
753.Em security
754risk if less memory is returned than intended.
755Subsequent code may corrupt the heap by writing beyond the memory that was
756allocated.
757An attacker may be able to leverage this heap corruption to execute arbitrary
758code.
759.Pp
760Consider using
761.Fn calloc ,
762.Fn reallocarray
763or
764.Fn recallocarray
765instead of using multiplication in
766.Fn malloc
767and
768.Fn realloc
769to avoid these problems on
770.Ox .
771