xref: /openbsd/lib/libc/stdlib/malloc.3 (revision 8529ddd3)
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.90 2015/03/14 08:07:17 tedu Exp $
34.\"
35.Dd $Mdocdate: March 14 2015 $
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.Nd memory allocation and deallocation
45.Sh SYNOPSIS
46.In stdlib.h
47.Ft void *
48.Fn malloc "size_t size"
49.Ft void *
50.Fn calloc "size_t nmemb" "size_t size"
51.Ft void *
52.Fn reallocarray "void *ptr" "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 char * Ns
58.Va malloc_options ;
59.Sh DESCRIPTION
60The
61.Fn malloc
62function allocates uninitialized space for an object of
63the specified
64.Fa size .
65.Fn malloc
66maintains multiple lists of free blocks according to size, allocating
67space from the appropriate list.
68The allocated space is suitably aligned (after possible pointer coercion) for
69storage of any type of object.
70If the space is of
71.Em pagesize
72or larger, the memory returned will be page-aligned.
73.Pp
74The
75.Fn calloc
76function allocates space for an array of
77.Fa nmemb
78objects, each of the specified
79.Fa size .
80The space is initialized to zero.
81.Pp
82The
83.Fn realloc
84function changes the size of the object pointed to by
85.Fa ptr
86to
87.Fa size
88bytes and returns a pointer to the (possibly moved) object.
89The contents of the object are unchanged up to the lesser
90of the new and old sizes.
91If the new size is larger, the value of the newly allocated portion
92of the object is indeterminate and uninitialized.
93If the space cannot be allocated, the object
94pointed to by
95.Fa ptr
96is unchanged.
97If
98.Fa ptr
99is
100.Dv NULL ,
101.Fn realloc
102behaves like
103.Fn malloc
104and allocates a new object.
105.Pp
106The
107.Fn reallocarray
108function is similar to
109.Fn realloc
110except it operates on
111.Fa nmemb
112members of size
113.Fa size
114and checks for integer overflow in the calculation
115.Fa nmemb
116*
117.Fa size .
118.Pp
119The
120.Fn free
121function causes the space pointed to by
122.Fa ptr
123to be either placed on a list of free pages to make it available for future
124allocation or, if required, to be returned to the kernel using
125.Xr munmap 2 .
126If
127.Fa ptr
128is a
129.Dv NULL
130pointer, no action occurs.
131If
132.Fa ptr
133was previously freed by
134.Fn free ,
135.Fn realloc ,
136or
137.Fn reallocarray ,
138the behavior is undefined and the double free is a security concern.
139.Sh RETURN VALUES
140Upon successful completion, the functions
141.Fn malloc ,
142.Fn calloc ,
143.Fn realloc ,
144and
145.Fn reallocarray
146return a pointer to the allocated space; otherwise, a
147.Dv NULL
148pointer is returned and
149.Va errno
150is set to
151.Er ENOMEM .
152.Pp
153If
154.Fa size
155or
156.Fa nmemb
157is equal to 0, a unique pointer to an access protected,
158zero sized object is returned.
159Access via this pointer will generate a
160.Dv SIGSEGV
161exception.
162.Pp
163If multiplying
164.Fa nmemb
165and
166.Fa size
167results in integer overflow,
168.Fn calloc
169and
170.Fn reallocarray
171return
172.Dv NULL
173and set
174.Va errno
175to
176.Er ENOMEM .
177.Pp
178The
179.Fn free
180function returns no value.
181.Sh IDIOMS
182Consider
183.Fn calloc
184or the extension
185.Fn reallocarray
186when there is multiplication in the
187.Fa size
188argument of
189.Fn malloc
190or
191.Fn realloc .
192For example, avoid this common idiom as it may lead to integer overflow:
193.Bd -literal -offset indent
194if ((p = malloc(num * size)) == NULL)
195	err(1, "malloc");
196.Ed
197.Pp
198A drop-in replacement is the
199.Ox
200extension
201.Fn reallocarray :
202.Bd -literal -offset indent
203if ((p = reallocarray(NULL, num, size)) == NULL)
204	err(1, "reallocarray");
205.Ed
206.Pp
207Alternatively,
208.Fn calloc
209may be used at the cost of initialization overhead.
210.Pp
211When using
212.Fn realloc ,
213be careful to avoid the following idiom:
214.Bd -literal -offset indent
215size += 50;
216if ((p = realloc(p, size)) == NULL)
217	return (NULL);
218.Ed
219.Pp
220Do not adjust the variable describing how much memory has been allocated
221until the allocation has been successful.
222This can cause aberrant program behavior if the incorrect size value is used.
223In most cases, the above sample will also result in a leak of memory.
224As stated earlier, a return value of
225.Dv NULL
226indicates that the old object still remains allocated.
227Better code looks like this:
228.Bd -literal -offset indent
229newsize = size + 50;
230if ((newp = realloc(p, newsize)) == NULL) {
231	free(p);
232	p = NULL;
233	size = 0;
234	return (NULL);
235}
236p = newp;
237size = newsize;
238.Ed
239.Pp
240As with
241.Fn malloc ,
242it is important to ensure the new size value will not overflow;
243i.e. avoid allocations like the following:
244.Bd -literal -offset indent
245if ((newp = realloc(p, num * size)) == NULL) {
246	...
247.Ed
248.Pp
249Instead, use
250.Fn reallocarray :
251.Bd -literal -offset indent
252if ((newp = reallocarray(p, num, size)) == NULL) {
253	...
254.Ed
255.Pp
256Calling
257.Fn realloc
258with a
259.Dv NULL
260.Fa ptr
261is equivalent to calling
262.Fn malloc .
263Instead of this idiom:
264.Bd -literal -offset indent
265if (p == NULL)
266	newp = malloc(newsize);
267else
268	newp = realloc(p, newsize);
269.Ed
270.Pp
271Use the following:
272.Bd -literal -offset indent
273newp = realloc(p, newsize);
274.Ed
275.Sh ENVIRONMENT
276.Bl -tag -width "/etc/malloc.conf"
277.It Ev MALLOC_OPTIONS
278String of flags documented in
279.Xr malloc.conf 5 .
280.El
281.Sh FILES
282.Bl -tag -width "/etc/malloc.conf"
283.It Pa /etc/malloc.conf
284Symbolic link to filename containing option flags.
285.El
286.Sh EXAMPLES
287If
288.Fn malloc
289must be used with multiplication, be sure to test for overflow:
290.Bd -literal -offset indent
291size_t num, size;
292\&...
293
294/* Check for size_t overflow */
295if (size && num > SIZE_MAX / size)
296	errc(1, EOVERFLOW, "overflow");
297
298if ((p = malloc(size * num)) == NULL)
299	err(1, "malloc");
300.Ed
301.Pp
302The above test is not sufficient in all cases.
303For example, multiplying ints requires a different set of checks:
304.Bd -literal -offset indent
305int num, size;
306\&...
307
308/* Avoid invalid requests */
309if (size < 0 || num < 0)
310	errc(1, EOVERFLOW, "overflow");
311
312/* Check for signed int overflow */
313if (size && num > INT_MAX / size)
314	errc(1, EOVERFLOW, "overflow");
315
316if ((p = malloc(size * num)) == NULL)
317	err(1, "malloc");
318.Ed
319.Pp
320Assuming the implementation checks for integer overflow as
321.Ox
322does, it is much easier to use
323.Fn calloc
324or
325.Fn reallocarray .
326.Pp
327The above examples could be simplified to:
328.Bd -literal -offset indent
329if ((p = reallocarray(NULL, num, size)) == NULL)
330	err(1, "reallocarray");
331.Ed
332.Pp
333or at the cost of initialization:
334.Bd -literal -offset indent
335if ((p = calloc(num, size)) == NULL)
336	err(1, "calloc");
337.Ed
338.Sh DIAGNOSTICS
339If
340.Fn malloc ,
341.Fn calloc ,
342.Fn realloc ,
343.Fn reallocarray ,
344or
345.Fn free
346detect an error condition,
347a message will be printed to file descriptor
3482 (not using stdio).
349Errors will result in the process being aborted,
350unless the
351.Cm a
352option has been specified.
353.Pp
354Here is a brief description of the error messages and what they mean:
355.Bl -tag -width Ds
356.It Dq out of memory
357If the
358.Cm X
359option is specified it is an error for
360.Fn malloc ,
361.Fn calloc ,
362.Fn realloc ,
363or
364.Fn reallocarray
365to return
366.Dv NULL .
367.It Dq malloc init mmap failed
368This is a rather weird condition that is most likely to indicate a
369seriously overloaded system or a ulimit restriction.
370.It Dq bogus pointer (double free?)
371An attempt to
372.Fn free ,
373.Fn realloc ,
374or
375.Fn reallocarray
376an unallocated pointer was made.
377.It Dq chunk is already free
378There was an attempt to free a chunk that had already been freed.
379.It Dq modified chunk-pointer
380The pointer passed to
381.Fn free ,
382.Fn realloc ,
383or
384.Fn reallocarray
385has been modified.
386.It Dq recursive call
387An attempt was made to call recursively into these functions, i.e., from a
388signal handler.
389This behavior is not supported.
390In particular, signal handlers should
391.Em not
392use any of the
393.Fn malloc
394functions nor utilize any other functions which may call
395.Fn malloc
396(e.g.,
397.Xr stdio 3
398routines).
399.It Dq unknown char in MALLOC_OPTIONS
400We found something we didn't understand.
401.It Dq malloc cache overflow/underflow
402The internal malloc page cache has been corrupted.
403.It Dq malloc free slot lost
404The internal malloc page cache has been corrupted.
405.It Dq guard size
406An inconsistent guard size was detected.
407.It any other error
408.Fn malloc
409detected an internal error;
410consult sources and/or wizards.
411.El
412.Sh SEE ALSO
413.Xr brk 2 ,
414.Xr mmap 2 ,
415.Xr munmap 2 ,
416.Xr alloca 3 ,
417.Xr getpagesize 3 ,
418.Xr posix_memalign 3 ,
419.Xr sysconf 3 ,
420.Xr malloc.conf 5
421.Sh STANDARDS
422The
423.Fn malloc ,
424.Fn calloc ,
425.Fn realloc ,
426and
427.Fn free
428functions conform to
429.St -ansiC .
430.Pp
431If
432.Fa size
433or
434.Fa nmemb
435are 0, the return value is implementation defined;
436other conforming implementations may return
437.Dv NULL
438in this case.
439.Pp
440The
441.Ev MALLOC_OPTIONS
442environment variable, the file
443.Pa /etc/malloc.conf ,
444and the
445.Sx DIAGNOSTICS
446output are extensions to the standard.
447.Sh HISTORY
448A
449.Fn free
450internal kernel function and a predecessor to
451.Fn malloc ,
452.Fn alloc ,
453first appeared in
454.At v1 .
455C library functions
456.Fn alloc
457and
458.Fn free
459appeared in
460.At v6 .
461The functions
462.Fn malloc ,
463.Fn calloc ,
464and
465.Fn realloc
466first appeared in
467.At v7 .
468.Pp
469A new implementation by Chris Kingsley was introduced in
470.Bx 4.2 ,
471followed by a complete rewrite by Poul-Henning Kamp which appeared in
472.Fx 2.2
473and was included in
474.Ox 2.0 .
475These implementations were all
476.Xr sbrk 2
477based.
478In
479.Ox 3.8 ,
480Thierry Deval rewrote
481.Nm
482to use the
483.Xr mmap 2
484system call,
485making the page addresses returned by
486.Nm
487random.
488A rewrite by Otto Moerbeek introducing a new central data structure and more
489randomization appeared in
490.Ox 4.4 .
491.Pp
492The
493.Fn reallocarray
494function appeared in
495.Ox 5.6 .
496.Sh CAVEATS
497When using
498.Fn malloc ,
499be wary of signed integer and
500.Vt size_t
501overflow especially when there is multiplication in the
502.Fa size
503argument.
504.Pp
505Signed integer overflow will cause undefined behavior which compilers
506typically handle by wrapping back around to negative numbers.
507Depending on the input, this can result in allocating more or less
508memory than intended.
509.Pp
510An unsigned overflow has defined behavior which will wrap back around and
511return less memory than intended.
512.Pp
513A signed or unsigned integer overflow is a
514.Em security
515risk if less memory is returned than intended.
516Subsequent code may corrupt the heap by writing beyond the memory that was
517allocated.
518An attacker may be able to leverage this heap corruption to execute arbitrary
519code.
520.Pp
521Consider using
522.Fn calloc
523or
524.Fn reallocarray
525instead of using multiplication in
526.Fn malloc
527and
528.Fn realloc
529to avoid these problems on
530.Ox .
531