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.\"	$MirOS: src/lib/libc/stdlib/malloc.3,v 1.6 2014/03/02 14:45:04 tg Exp $
34.\"	$OpenBSD: malloc.3,v 1.73 2013/07/18 10:14:49 schwarze Exp $
35.\"
36.Dd $Mdocdate: March 2 2014 $
37.Dt MALLOC 3
38.Os
39.Sh NAME
40.Nm malloc ,
41.Nm calloc ,
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 realloc "void *ptr" "size_t size"
54.Ft void
55.Fn free "void *ptr"
56.Ft void
57.Fn cfree "void *ptr"
58.Ft char *
59.Va malloc_options ;
60.Sh DESCRIPTION
61Note: if using
62.Xr brk 2
63malloc or
64.Xr mmap 2
65malloc instead of
66.Nm omalloc ,
67this manual page is inaccurate,
68especially regarding the protection functions.
69.Pp
70The
71.Fn malloc
72function allocates uninitialized space for an object whose
73size is specified by
74.Fa size .
75The
76.Fn malloc
77function maintains multiple lists of free blocks according to size, allocating
78space from the appropriate list.
79.Pp
80The allocated space is
81suitably aligned (after possible pointer
82coercion) for storage of any type of object.
83If the space is of
84.Em pagesize
85or larger, the memory returned will be page-aligned.
86.Pp
87Allocation of a zero size object returns a pointer to a zero size object.
88This zero size object is access protected, so any access to it will
89generate an exception (SIGSEGV).
90Many zero-sized objects can be placed consecutively in shared
91protected pages.
92The minimum size of the protection on each object is suitably aligned and
93sized as previously stated, but the protection may extend further depending
94on where in a protected zone the object lands.
95.Pp
96When using
97.Fn malloc
98be careful to avoid the following idiom:
99.Bd -literal -offset indent
100if ((p = malloc(num * size)) == NULL)
101	err(1, "malloc");
102.Ed
103.Pp
104The multiplication may lead to an integer overflow.
105To avoid this,
106.Fn calloc
107is recommended.
108.Pp
109If
110.Fn malloc
111must be used, be sure to test for overflow:
112.Bd -literal -offset indent
113if (size && num > SIZE_MAX / size) {
114	errno = ENOMEM;
115	err(1, "overflow");
116}
117.Ed
118.Pp
119The
120.Fn calloc
121function allocates space for an array of
122.Fa nmemb
123objects, each of whose size is
124.Fa size .
125The space is initialized to zero.
126The use of
127.Fn calloc
128is strongly encouraged when allocating multiple sized objects
129in order to avoid possible integer overflows.
130.Pp
131The
132.Fn free
133function causes the space pointed to by
134.Fa ptr
135to be either placed on a list of free pages to make it available for future
136allocation or, if required, to be returned to the kernel using
137.Xr munmap 2 .
138If
139.Fa ptr
140is a null pointer, no action occurs.
141.Pp
142A
143.Fn cfree
144function is also provided for compatibility with old systems and other
145.Nm malloc
146libraries; it is simply an alias for
147.Fn free .
148.Pp
149The
150.Fn realloc
151function changes the size of the object pointed to by
152.Fa ptr
153to
154.Fa size
155bytes and returns a pointer to the (possibly moved) object.
156The contents of the object are unchanged up to the lesser
157of the new and old sizes.
158If the new size is larger, the value of the newly allocated portion
159of the object is indeterminate and uninitialized.
160If
161.Fa ptr
162is a null pointer, the
163.Fn realloc
164function behaves like the
165.Fn malloc
166function for the specified size.
167If the space cannot be allocated, the object
168pointed to by
169.Fa ptr
170is unchanged.
171If
172.Fa size
173is zero and
174.Fa ptr
175is not a null pointer, the object it points to is freed and a new zero size
176object is returned.
177.Pp
178When using
179.Fn realloc
180be careful to avoid the following idiom:
181.Bd -literal -offset indent
182size += 50;
183if ((p = realloc(p, size)) == NULL)
184	return (NULL);
185.Ed
186.Pp
187Do not adjust the variable describing how much memory has been allocated
188until the allocation has been successful.
189This can cause aberrant program behavior if the incorrect size value is used.
190In most cases, the above sample will also result in a leak of memory.
191As stated earlier, a return value of
192.Dv NULL
193indicates that the old object still remains allocated.
194Better code looks like this:
195.Bd -literal -offset indent
196newsize = size + 50;
197if ((newp = realloc(p, newsize)) == NULL) {
198	free(p);
199	p = NULL;
200	size = 0;
201	return (NULL);
202}
203p = newp;
204size = newsize;
205.Ed
206.Pp
207As with
208.Fn malloc
209it is important to ensure the new size value will not overflow;
210i.e. avoid allocations like the following:
211.Bd -literal -offset indent
212if ((newp = realloc(p, num * size)) == NULL) {
213	...
214.Ed
215.Sh MALLOC_OPTIONS
216Malloc will first look for a symbolic link called
217.Pa /etc/malloc.conf
218and next check the environment for a variable called
219.Ev MALLOC_OPTIONS
220and finally for the global variable
221.Va malloc_options
222and scan them for flags in that order.
223Flags are single letters, uppercase means on, lowercase means off.
224.Bl -tag -width indent
225.It Cm A
226.Dq Abort .
227.Fn malloc
228will coredump the process, rather than tolerate internal
229inconsistencies or incorrect usage.
230This is the default and a very handy debugging aid,
231since the core file represents the time of failure,
232rather than when the bogus pointer was used.
233.It Cm D
234.Dq Dump .
235.Fn malloc
236will dump statistics to the file
237.Pa ./malloc.out ,
238if it already exists,
239at exit.
240This option requires the library to have been compiled with -DMALLOC_STATS in
241order to have any effect.
242.It Cm F
243.Dq Freeguard .
244Enable use after free detection.
245Unused pages on the freelist are read and write protected to
246cause a segmentation fault upon access.
247This will also switch off the delayed freeing of chunks,
248reducing random behaviour but detecting double
249.Fn free
250calls as early as possible.
251This option is intended for debugging rather than improved security
252(use the
253.Cm U
254option for security).
255.It Cm G
256.Dq Guard .
257Enable guard pages.
258Each page size or larger allocation is followed by a guard page that will
259cause a segmentation fault upon any access.
260.It Cm H
261.Dq Hint .
262Pass a hint to the kernel about pages we don't use.
263If the machine is paging a lot this may help a bit.
264.It Cm J
265.Dq Junk .
266Fill some junk into the area allocated.
267Currently junk is bytes of 0xd0 when allocating; this is pronounced
268.Dq Duh .
269\&:-)
270Freed chunks are filled with 0xdf.
271.It Cm P
272.Dq Move allocations within a page.
273Allocations larger than half a page but smaller than a page
274are aligned to the end of a page to catch buffer overruns in more
275cases.
276This is the default.
277.It Cm R
278.Dq realloc .
279Always reallocate when
280.Fn realloc
281is called, even if the initial allocation was big enough.
282This can substantially aid in compacting memory.
283.\".Pp
284.\".It Cm U
285.\".Dq utrace .
286.\"Generate entries for
287.\".Xr ktrace 1
288.\"for all operations.
289.\"Consult the source for this one.
290.It Cm S
291Enable all options suitable for security auditing.
292.It Cm U
293.Dq Free unmap .
294Enable use after free protection for larger allocations.
295Unused pages on the freelist are read and write protected to
296cause a segmentation fault upon access.
297.It Cm X
298.Dq xmalloc .
299Rather than return failure,
300.Xr abort 3
301the program with a diagnostic message on stderr.
302It is the intention that this option be set at compile time by
303including in the source:
304.Bd -literal -offset indent
305extern char *malloc_options;
306malloc_options = "X";
307.Ed
308.Pp
309Note that this will cause code that is supposed to handle
310out-of-memory conditions gracefully to abort instead.
311.It Cm Z
312.Dq Zero .
313Fill some junk into the area allocated (see
314.Cm J ) ,
315except for the exact length the user asked for, which is zeroed.
316.It Cm <
317.Dq Half the cache size .
318Decrease the size of the free page cache by a factor of two.
319.It Cm >
320.Dq Double the cache size .
321Increase the size of the free page cache by a factor of two.
322.El
323.Pp
324So to set a systemwide reduction of the cache to a quarter of the
325default size and use guard pages:
326.Dl # ln -s 'G\*(Lt\*(Lt' /etc/malloc.conf
327.Pp
328The flags are mostly for testing and debugging.
329If a program changes behavior if any of these options (except
330.Cm X )
331are used,
332it is buggy.
333.Pp
334The default number of free pages cached is 64.
335.Sh RETURN VALUES
336The
337.Fn malloc
338and
339.Fn calloc
340functions return a pointer to the allocated space if successful; otherwise,
341a null pointer is returned and
342.Va errno
343is set to
344.Er ENOMEM .
345.Pp
346The
347.Fn free
348and
349.Fn cfree
350functions return no value.
351.Pp
352The
353.Fn realloc
354function returns a pointer to the (possibly moved) allocated space
355if successful; otherwise, a null pointer is returned and
356.Va errno
357is set to
358.Er ENOMEM .
359.Sh ENVIRONMENT
360.Bl -tag -width Ev
361.It Ev MALLOC_OPTIONS
362See above.
363.El
364.Sh FILES
365.Bl -tag -width "/etc/malloc.conf"
366.It Pa /etc/malloc.conf
367symbolic link to filename containing option flags
368.El
369.Sh DIAGNOSTICS
370If
371.Fn malloc ,
372.Fn calloc ,
373.Fn realloc ,
374or
375.Fn free
376detect an error condition,
377a message will be printed to file descriptor
3782 (not using stdio).
379Errors will result in the process being aborted,
380unless the
381.Cm a
382option has been specified.
383.Pp
384Here is a brief description of the error messages and what they mean:
385.Bl -tag -width Ds
386.It Dq out of memory
387If the
388.Cm X
389option is specified it is an error for
390.Fn malloc ,
391.Fn calloc ,
392or
393.Fn realloc
394to return
395.Dv NULL .
396.It Dq malloc init mmap failed
397This is a rather weird condition that is most likely to indicate a
398seriously overloaded system or a ulimit restriction.
399.It Dq bogus pointer (double free?)
400An attempt to
401.Fn free
402or
403.Fn realloc
404an unallocated pointer was made.
405.It Dq chunk is already free
406There was an attempt to free a chunk that had already been freed.
407.It Dq modified chunk-pointer
408The pointer passed to
409.Fn free
410or
411.Fn realloc
412has been modified.
413.It Dq recursive call
414An attempt was made to call recursively into these functions, i.e., from a
415signal handler.
416This behavior is not supported.
417In particular, signal handlers should
418.Em not
419use any of the
420.Fn malloc
421functions nor utilize any other functions which may call
422.Fn malloc
423(e.g.,
424.Xr stdio 3
425routines).
426.It Dq unknown char in MALLOC_OPTIONS
427We found something we didn't understand.
428.It Dq malloc cache overflow/underflow
429The internal malloc page cache has been corrupted.
430.It Dq malloc free slot lost
431The internal malloc page cache has been corrupted.
432.It Dq guard size
433An inconsistent guard size was detected.
434.It any other error
435.Fn malloc
436detected an internal error;
437consult sources and/or wizards.
438.El
439.Sh SEE ALSO
440.Xr brk 2 ,
441.Xr mmap 2 ,
442.Xr munmap 2 ,
443.Xr alloca 3 ,
444.Xr getpagesize 3 ,
445.Xr posix_memalign 3
446.Sh STANDARDS
447The
448.Fn malloc
449function conforms to
450.St -ansiC .
451.Sh HISTORY
452A
453.Fn free
454internal kernel function and a predecessor to
455.Fn malloc ,
456.Fn alloc ,
457first appeared in
458.At v1 .
459C library functions
460.Fn alloc
461and
462.Fn free
463appeared in
464.At v6 .
465The functions
466.Fn malloc ,
467.Fn calloc ,
468and
469.Fn realloc
470first appeared in
471.At v7 .
472.Pp
473A new implementation by Chris Kingsley was introduced in
474.Bx 4.2 ,
475followed by a complete rewrite by Poul-Henning Kamp which appeared in
476.Fx 2.2
477and was included in
478.Ox 2.0 .
479These implementations were all
480.Xr sbrk 2
481based.
482In
483.Ox 3.8 ,
484Thierry Deval rewrote
485.Nm
486to use the
487.Xr mmap 2
488system call,
489making the page addresses returned by
490.Nm
491random.
492A rewrite by Otto Moerbeek introducing a new central data structure and more
493randomization appeared in
494.Ox 4.4 .
495