xref: /openbsd-src/lib/libc/stdlib/malloc.3 (revision e5157e49389faebcb42b7237d55fbf096d9c2523)
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.85 2014/10/30 21:47:47 deraadt Exp $
34.\"
35.Dd $Mdocdate: October 30 2014 $
36.Dt MALLOC 3
37.Os
38.Sh NAME
39.Nm malloc ,
40.Nm calloc ,
41.Nm reallocarray ,
42.Nm realloc ,
43.Nm free ,
44.Nm cfree
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 realloc "void *ptr" "size_t size"
56.Ft void
57.Fn free "void *ptr"
58.Ft void
59.Fn cfree "void *ptr"
60.Ft char * Ns
61.Va malloc_options ;
62.Sh DESCRIPTION
63The
64.Fn malloc
65function allocates uninitialized space for an object of
66the specified
67.Fa size .
68.Fn malloc
69maintains multiple lists of free blocks according to size, allocating
70space from the appropriate list.
71The allocated space is suitably aligned (after possible pointer coercion) for
72storage of any type of object.
73If the space is of
74.Em pagesize
75or larger, the memory returned will be page-aligned.
76.Pp
77The
78.Fn calloc
79function allocates space for an array of
80.Fa nmemb
81objects, each of the specified
82.Fa size .
83The space is initialized to zero.
84.Pp
85The
86.Fn realloc
87function changes the size of the object pointed to by
88.Fa ptr
89to
90.Fa size
91bytes and returns a pointer to the (possibly moved) object.
92The contents of the object are unchanged up to the lesser
93of the new and old sizes.
94If the new size is larger, the value of the newly allocated portion
95of the object is indeterminate and uninitialized.
96If the space cannot be allocated, the object
97pointed to by
98.Fa ptr
99is unchanged.
100If
101.Fa ptr
102is
103.Dv NULL ,
104.Fn realloc
105behaves like
106.Fn malloc
107and allocates a new object.
108.Pp
109The
110.Fn reallocarray
111function is similar to
112.Fn realloc
113except it operates on
114.Fa nmemb
115members of size
116.Fa size
117and checks for integer overflow in the calculation
118.Fa nmemb
119*
120.Fa size .
121.Pp
122The
123.Fn free
124function causes the space pointed to by
125.Fa ptr
126to be either placed on a list of free pages to make it available for future
127allocation or, if required, to be returned to the kernel using
128.Xr munmap 2 .
129If
130.Fa ptr
131is a
132.Dv NULL
133pointer, no action occurs.
134If
135.Fa ptr
136was previously freed by
137.Fn free
138.Fn realloc ,
139or
140.Fn reallocarray ,
141the behavior is undefined and the double free is a security concern.
142.Pp
143A
144.Fn cfree
145function is also provided for compatibility with old systems and other
146.Nm malloc
147libraries; it is simply an alias for
148.Fn free .
149.Sh RETURN VALUES
150Upon successful completion, the functions
151.Fn malloc ,
152.Fn calloc ,
153.Fn realloc ,
154and
155.Fn reallocarray
156return a pointer to the allocated space; otherwise, a
157.Dv NULL
158pointer is returned and
159.Va errno
160is set to
161.Er ENOMEM .
162.Pp
163If
164.Fa size
165or
166.Fa nmemb
167is equal to 0, a unique pointer to an access protected,
168zero sized object is returned.
169Access via this pointer will generate a
170.Dv SIGSEGV
171exception.
172.Pp
173If multiplying
174.Fa nmemb
175and
176.Fa size
177results in integer overflow,
178.Fn calloc
179and
180.Fn reallocarray
181return
182.Dv NULL
183and set
184.Va errno
185to
186.Er ENOMEM .
187.Pp
188The
189.Fn free
190and
191.Fn cfree
192functions return no value.
193.Sh IDIOMS
194Consider
195.Fn calloc
196or the extension
197.Fn reallocarray
198when there is multiplication in the
199.Fa size
200argument of
201.Fn malloc
202or
203.Fn realloc .
204For example, avoid this common idiom as it may lead to integer overflow:
205.Bd -literal -offset indent
206if ((p = malloc(num * size)) == NULL)
207	err(1, "malloc");
208.Ed
209.Pp
210A drop-in replacement is the
211.Ox
212extension
213.Fn reallocarray :
214.Bd -literal -offset indent
215if ((p = reallocarray(NULL, num, size)) == NULL)
216	err(1, "reallocarray");
217.Ed
218.Pp
219Alternatively,
220.Fn calloc
221may be used at the cost of initialization overhead.
222.Pp
223When using
224.Fn realloc ,
225be careful to avoid the following idiom:
226.Bd -literal -offset indent
227size += 50;
228if ((p = realloc(p, size)) == NULL)
229	return (NULL);
230.Ed
231.Pp
232Do not adjust the variable describing how much memory has been allocated
233until the allocation has been successful.
234This can cause aberrant program behavior if the incorrect size value is used.
235In most cases, the above sample will also result in a leak of memory.
236As stated earlier, a return value of
237.Dv NULL
238indicates that the old object still remains allocated.
239Better code looks like this:
240.Bd -literal -offset indent
241newsize = size + 50;
242if ((newp = realloc(p, newsize)) == NULL) {
243	free(p);
244	p = NULL;
245	size = 0;
246	return (NULL);
247}
248p = newp;
249size = newsize;
250.Ed
251.Pp
252As with
253.Fn malloc ,
254it is important to ensure the new size value will not overflow;
255i.e. avoid allocations like the following:
256.Bd -literal -offset indent
257if ((newp = realloc(p, num * size)) == NULL) {
258	...
259.Ed
260.Pp
261Instead, use
262.Fn reallocarray :
263.Bd -literal -offset indent
264if ((newp = reallocarray(p, num, size)) == NULL) {
265	...
266.Ed
267.Pp
268Calling
269.Fn realloc
270with a
271.Dv NULL
272.Fa ptr
273is equivalent to calling
274.Fn malloc .
275Instead of this idiom:
276.Bd -literal -offset indent
277if (p == NULL)
278	newp = malloc(newsize);
279else
280	newp = realloc(p, newsize);
281.Ed
282.Pp
283Use the following:
284.Bd -literal -offset indent
285newp = realloc(p, newsize);
286.Ed
287.Sh ENVIRONMENT
288.Bl -tag -width Ev
289.It Ev MALLOC_OPTIONS
290See below.
291.El
292.Sh FILES
293.Bl -tag -width "/etc/malloc.conf"
294.It Pa /etc/malloc.conf
295symbolic link to filename containing option flags
296.El
297.Sh EXAMPLES
298If
299.Fn malloc
300must be used with multiplication, be sure to test for overflow:
301.Bd -literal -offset indent
302size_t num, size;
303\&...
304
305/* Check for size_t overflow */
306if (size && num > SIZE_MAX / size)
307	errc(1, EOVERFLOW, "overflow");
308
309if ((p = malloc(size * num)) == NULL)
310	err(1, "malloc");
311.Ed
312.Pp
313The above test is not sufficient in all cases.
314For example, multiplying ints requires a different set of checks:
315.Bd -literal -offset indent
316int num, size;
317\&...
318
319/* Avoid invalid requests */
320if (size < 0 || num < 0)
321	errc(1, EOVERFLOW, "overflow");
322
323/* Check for signed int overflow */
324if (size && num > INT_MAX / size)
325	errc(1, EOVERFLOW, "overflow");
326
327if ((p = malloc(size * num)) == NULL)
328	err(1, "malloc");
329.Ed
330.Pp
331Assuming the implementation checks for integer overflow as
332.Ox
333does, it is much easier to use
334.Fn calloc
335or
336.Fn reallocarray .
337.Pp
338The above examples could be simplified to:
339.Bd -literal -offset indent
340if ((p = reallocarray(NULL, num, size)) == NULL)
341	err(1, "reallocarray");
342.Ed
343.Pp
344or at the cost of initialization:
345.Bd -literal -offset indent
346if ((p = calloc(num, size)) == NULL)
347	err(1, "calloc");
348.Ed
349.Sh DIAGNOSTICS
350If
351.Fn malloc ,
352.Fn calloc ,
353.Fn realloc ,
354.Fn reallocarray ,
355or
356.Fn free
357detect an error condition,
358a message will be printed to file descriptor
3592 (not using stdio).
360Errors will result in the process being aborted,
361unless the
362.Cm a
363option has been specified.
364.Pp
365Here is a brief description of the error messages and what they mean:
366.Bl -tag -width Ds
367.It Dq out of memory
368If the
369.Cm X
370option is specified it is an error for
371.Fn malloc ,
372.Fn calloc ,
373.Fn realloc ,
374or
375.Fn reallocarray
376to return
377.Dv NULL .
378.It Dq malloc init mmap failed
379This is a rather weird condition that is most likely to indicate a
380seriously overloaded system or a ulimit restriction.
381.It Dq bogus pointer (double free?)
382An attempt to
383.Fn free ,
384.Fn realloc ,
385or
386.Fn reallocarray
387an unallocated pointer was made.
388.It Dq chunk is already free
389There was an attempt to free a chunk that had already been freed.
390.It Dq modified chunk-pointer
391The pointer passed to
392.Fn free ,
393.Fn realloc ,
394or
395.Fn reallocarray
396has been modified.
397.It Dq recursive call
398An attempt was made to call recursively into these functions, i.e., from a
399signal handler.
400This behavior is not supported.
401In particular, signal handlers should
402.Em not
403use any of the
404.Fn malloc
405functions nor utilize any other functions which may call
406.Fn malloc
407(e.g.,
408.Xr stdio 3
409routines).
410.It Dq unknown char in MALLOC_OPTIONS
411We found something we didn't understand.
412.It Dq malloc cache overflow/underflow
413The internal malloc page cache has been corrupted.
414.It Dq malloc free slot lost
415The internal malloc page cache has been corrupted.
416.It Dq guard size
417An inconsistent guard size was detected.
418.It any other error
419.Fn malloc
420detected an internal error;
421consult sources and/or wizards.
422.El
423.Sh MALLOC_OPTIONS
424Malloc will first look for a symbolic link called
425.Pa /etc/malloc.conf
426and next check the environment for a variable called
427.Ev MALLOC_OPTIONS
428and finally for the global variable
429.Va malloc_options
430and scan them for flags in that order.
431Flags are single letters, uppercase means on, lowercase means off.
432.Bl -tag -width indent
433.It Cm A
434.Dq Abort .
435.Fn malloc
436will coredump the process, rather than tolerate internal
437inconsistencies or incorrect usage.
438This is the default and a very handy debugging aid,
439since the core file represents the time of failure,
440rather than when the bogus pointer was used.
441.It Cm D
442.Dq Dump .
443.Fn malloc
444will dump statistics to the file
445.Pa ./malloc.out ,
446if it already exists,
447at exit.
448This option requires the library to have been compiled with -DMALLOC_STATS in
449order to have any effect.
450.It Cm F
451.Dq Freeguard .
452Enable use after free detection.
453Unused pages on the freelist are read and write protected to
454cause a segmentation fault upon access.
455This will also switch off the delayed freeing of chunks,
456reducing random behaviour but detecting double
457.Fn free
458calls as early as possible.
459This option is intended for debugging rather than improved security
460(use the
461.Cm U
462option for security).
463.It Cm G
464.Dq Guard .
465Enable guard pages.
466Each page size or larger allocation is followed by a guard page that will
467cause a segmentation fault upon any access.
468.It Cm H
469.Dq Hint .
470Pass a hint to the kernel about pages we don't use.
471If the machine is paging a lot this may help a bit.
472.It Cm J
473.Dq Junk .
474Fill some junk into the area allocated.
475Currently junk is bytes of 0xd0 when allocating; this is pronounced
476.Dq Duh .
477\&:-)
478Freed chunks are filled with 0xdf.
479.It Cm j
480.Dq Don't Junk .
481By default, small chunks are always junked, and the first part of pages
482is junked after free.
483This option ensures that no junking is performed.
484.It Cm P
485.Dq Move allocations within a page.
486Allocations larger than half a page but smaller than a page
487are aligned to the end of a page to catch buffer overruns in more
488cases.
489This is the default.
490.It Cm R
491.Dq realloc .
492Always reallocate when
493.Fn realloc
494is called, even if the initial allocation was big enough.
495This can substantially aid in compacting memory.
496.\".Pp
497.\".It Cm U
498.\".Dq utrace .
499.\"Generate entries for
500.\".Xr ktrace 1
501.\"for all operations.
502.\"Consult the source for this one.
503.It Cm S
504Enable all options suitable for security auditing.
505.It Cm U
506.Dq Free unmap .
507Enable use after free protection for larger allocations.
508Unused pages on the freelist are read and write protected to
509cause a segmentation fault upon access.
510.It Cm X
511.Dq xmalloc .
512Rather than return failure,
513.Xr abort 3
514the program with a diagnostic message on stderr.
515It is the intention that this option be set at compile time by
516including in the source:
517.Bd -literal -offset indent
518extern char *malloc_options;
519malloc_options = "X";
520.Ed
521.Pp
522Note that this will cause code that is supposed to handle
523out-of-memory conditions gracefully to abort instead.
524.It Cm <
525.Dq Half the cache size .
526Decrease the size of the free page cache by a factor of two.
527.It Cm >
528.Dq Double the cache size .
529Increase the size of the free page cache by a factor of two.
530.El
531.Pp
532So to set a systemwide reduction of the cache to a quarter of the
533default size and use guard pages:
534.Dl # ln -s 'G<<' /etc/malloc.conf
535.Pp
536The flags are mostly for testing and debugging.
537If a program changes behavior if any of these options (except
538.Cm X )
539are used,
540it is buggy.
541.Pp
542The default number of free pages cached is 64.
543.Sh SEE ALSO
544.Xr brk 2 ,
545.Xr mmap 2 ,
546.Xr munmap 2 ,
547.Xr alloca 3 ,
548.Xr getpagesize 3 ,
549.Xr posix_memalign 3 ,
550.Xr sysconf 3
551.Sh STANDARDS
552The
553.Fn malloc ,
554.Fn calloc ,
555.Fn realloc ,
556and
557.Fn free
558functions conform to
559.St -ansiC .
560.Pp
561If
562.Fa size
563or
564.Fa nmemb
565are 0, the return value is implementation defined;
566other conforming implementations may return
567.Dv NULL
568in this case.
569.Pp
570The standard does not require
571.Fn calloc
572to check for integer overflow,
573but most modern implementations provide this check.
574.Pp
575The
576.Ev MALLOC_OPTIONS
577environment variable, the file
578.Pa /etc/malloc.conf ,
579and the
580.Sx DIAGNOSTICS
581output are extensions to the standard.
582.Sh HISTORY
583A
584.Fn free
585internal kernel function and a predecessor to
586.Fn malloc ,
587.Fn alloc ,
588first appeared in
589.At v1 .
590C library functions
591.Fn alloc
592and
593.Fn free
594appeared in
595.At v6 .
596The functions
597.Fn malloc ,
598.Fn calloc ,
599and
600.Fn realloc
601first appeared in
602.At v7 .
603.Pp
604A new implementation by Chris Kingsley was introduced in
605.Bx 4.2 ,
606followed by a complete rewrite by Poul-Henning Kamp which appeared in
607.Fx 2.2
608and was included in
609.Ox 2.0 .
610These implementations were all
611.Xr sbrk 2
612based.
613In
614.Ox 3.8 ,
615Thierry Deval rewrote
616.Nm
617to use the
618.Xr mmap 2
619system call,
620making the page addresses returned by
621.Nm
622random.
623A rewrite by Otto Moerbeek introducing a new central data structure and more
624randomization appeared in
625.Ox 4.4 .
626.Pp
627The
628.Fn reallocarray
629function appeared in
630.Ox 5.6 .
631.Pp
632The
633.Fn cfree
634function appeared in SunOS 4.x.
635.Sh CAVEATS
636When using
637.Fn malloc ,
638be wary of signed integer and
639.Vt size_t
640overflow especially when there is multiplication in the
641.Fa size
642argument.
643.Pp
644Signed integer overflow will cause undefined behavior which compilers
645typically handle by wrapping back around to negative numbers.
646Depending on the input, this can result in allocating more or less
647memory than intended.
648.Pp
649An unsigned overflow has defined behavior which will wrap back around and
650return less memory than intended.
651.Pp
652A signed or unsigned integer overflow is a
653.Em security
654risk if less memory is returned than intended.
655Subsequent code may corrupt the heap by writing beyond the memory that was
656allocated.
657An attacker may be able to leverage this heap corruption to execute arbitrary
658code.
659.Pp
660Consider using
661.Fn calloc
662or
663.Fn reallocarray
664instead of using multiplication in
665.Fn malloc
666and
667.Fn realloc
668to avoid these problems on
669.Ox .
670