xref: /dragonfly/lib/libc/stdlib/malloc.3 (revision 678e8cc6)
1.\" $NetBSD: malloc.3,v 1.38 2010/05/03 08:23:20 jruoho Exp $
2.\"
3.\" Copyright (c) 1980, 1991, 1993
4.\"	The Regents of the University of California.  All rights reserved.
5.\"
6.\" This code is derived from software contributed to Berkeley by
7.\" the American National Standards Committee X3, on Information
8.\" Processing Systems.
9.\"
10.\" Redistribution and use in source and binary forms, with or without
11.\" modification, are permitted provided that the following conditions
12.\" are met:
13.\" 1. Redistributions of source code must retain the above copyright
14.\"    notice, this list of conditions and the following disclaimer.
15.\" 2. Redistributions in binary form must reproduce the above copyright
16.\"    notice, this list of conditions and the following disclaimer in the
17.\"    documentation and/or other materials provided with the distribution.
18.\" 3. All advertising materials mentioning features or use of this software
19.\"    must display the following acknowledgement:
20.\"	This product includes software developed by the University of
21.\"	California, Berkeley and its contributors.
22.\" 4. Neither the name of the University nor the names of its contributors
23.\"    may be used to endorse or promote products derived from this software
24.\"    without specific prior written permission.
25.\"
26.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36.\" SUCH DAMAGE.
37.\"
38.\"     @(#)malloc.3	8.1 (Berkeley) 6/4/93
39.\" $FreeBSD: src/lib/libc/stdlib/malloc.3,v 1.73 2007/06/15 22:32:33 jasone Exp $
40.\"
41.Dd May 21, 2010
42.Dt MALLOC 3
43.Os
44.Sh NAME
45.Nm malloc ,
46.Nm calloc ,
47.Nm realloc ,
48.Nm reallocf ,
49.Nm free ,
50.Nd general purpose memory allocation functions
51.Sh LIBRARY
52.Lb libc
53.Sh SYNOPSIS
54.In stdlib.h
55.Ft void *
56.Fn malloc "size_t size"
57.Ft void *
58.Fn calloc "size_t number" "size_t size"
59.Ft void *
60.Fn realloc "void *ptr" "size_t size"
61.Ft void *
62.Fn reallocf "void *ptr" "size_t size"
63.Ft void
64.Fn free "void *ptr"
65.Sh DESCRIPTION
66The
67.Fn malloc
68function allocates
69.Fa size
70bytes of uninitialized memory.
71The allocated space is suitably aligned (after possible pointer coercion)
72for storage of any type of object.
73If the space is at least
74.Em pagesize
75bytes in length (see
76.Xr getpagesize 3 ) ,
77the returned memory will be page boundary aligned as well.
78.Pp
79The
80.Fn calloc
81function allocates space for
82.Fa number
83objects,
84each
85.Fa size
86bytes in length.
87The result is identical to calling
88.Fn malloc
89with an argument of
90.Dq "number * size" ,
91with the exception that the allocated memory is explicitly initialized
92to zero bytes.
93.Pp
94The
95.Fn realloc
96function changes the size of the previously allocated memory referenced by
97.Fa ptr
98to
99.Fa size
100bytes.
101The contents of the memory are unchanged up to the lesser of the new and
102old sizes.
103If the new size is larger,
104the value of the newly allocated portion of the memory is undefined.
105Upon success, the memory referenced by
106.Fa ptr
107is freed and a pointer to the newly allocated memory is returned.
108Note that
109.Fn realloc
110may move the memory allocation, resulting in a different return value than
111.Fa ptr .
112If
113.Fa ptr
114is
115.Dv NULL ,
116the
117.Fn realloc
118function behaves identically to
119.Fn malloc
120for the specified size.
121.Pp
122The
123.Fn reallocf
124function call is identical to the realloc function call, except that it
125will free the passed pointer when the requested memory cannot be allocated.
126This is a
127.Fx
128/
129.Dx
130specific API designed to ease the problems with traditional coding styles
131for realloc causing memory leaks in libraries.
132.Pp
133The
134.Fn free
135function causes the allocated memory referenced by
136.Fa ptr
137to be made available for future allocations.
138If
139.Fa ptr
140is
141.Dv NULL ,
142no action occurs.
143.Sh IMPLEMENTATION NOTES
144.Dx Ap s
145.Nm
146implementation is based on a port of the
147.Dx
148kernel slab allocator, appropriately modified for a user process
149environment.
150.Pp
151The slab allocator breaks memory allocations up to 8KB into 80 zones.
152Each zone represents a fixed allocation size in multiples of some
153core chunking.
154The chunking is a power-of-2 but the fixed allocation size is not.
155For example, a 1025-byte request is allocated out of the zone with a
156chunking of 128, thus in multiples of 1152 bytes.
157The minimum chunking, used for allocations in the 0-127 byte range,
158is 8 bytes (16 of the 80 zones).
159Beyond that the power-of-2 chunking is between 1/8 and 1/16 of the
160minimum allocation size for any given zone.
161.Pp
162As a special case any power-of-2-sized allocation within the zone
163limit (8K) will be aligned to the same power-of-2 rather than that
164zone's (smaller) chunking.
165This is not something you can depend upon for
166.Fn malloc ,
167but it is used internally to optimize
168.Xr posix_memalign 3 .
169.Pp
170Each zone reserves memory in 64KB blocks.
171Actual memory use tends to be significantly less as only the pages
172actually needed are faulted in.
173Allocations larger than 8K are managed using
174.Xr mmap 2
175and tracked with a hash table.
176.Pp
177The zone mechanism results in well-fitted allocations with little
178waste in a long-running environment which makes a lot of allocations.
179Short-running environments which do not make many allocations will see
180a bit of extra bloat due to the large number of zones but it will
181be almost unnoticeable in the grand scheme of things.
182To reduce bloat further the normal randomized start offset implemented
183in the kernel version of the allocator to improve L1 cache fill is
184disabled in the libc version.
185.Pp
186The zone mechanism also has the nice side effect of greatly reducing
187fragmentation over the original
188.Nm .
189.Pp
190.Fn calloc
191is directly supported by keeping track of newly-allocated zones which
192will be demand-zero'd by the system.
193If the allocation is known to be zero'd we do not bother
194.Fn bzero Ns ing
195it.
196If it is a reused allocation we
197.Fn bzero .
198.Pp
199.Tn POSIX
200threading is supported by duplicating the primary structure.
201A thread entering
202.Fn malloc
203which is unable to immediately acquire a mutex on the last primary
204structure it used will switch to a different primary structure.
205At the moment this is more of a quick hack than a solution, but it works.
206.Sh RETURN VALUES
207The
208.Fn malloc
209and
210.Fn calloc
211functions return a pointer to the allocated memory if successful; otherwise
212a
213.Dv NULL
214pointer is returned and
215.Va errno
216is set to
217.Er ENOMEM .
218.Pp
219The
220.Fn realloc
221and
222.Fn reallocf
223functions return a pointer, possibly identical to
224.Fa ptr ,
225to the allocated memory
226if successful; otherwise a
227.Dv NULL
228pointer is returned, and
229.Va errno
230is set to
231.Er ENOMEM
232if the error was the result of an allocation failure.
233The
234.Fn realloc
235function always leaves the original buffer intact
236when an error occurs, whereas
237.Fn reallocf
238deallocates it in this case.
239.Pp
240The
241.Fn free
242function returns no value.
243.Sh EXAMPLES
244When using
245.Fn malloc ,
246be careful to avoid the following idiom:
247.Bd -literal -offset indent
248if ((p = malloc(number * size)) == NULL)
249	err(EXIT_FAILURE, "malloc");
250.Ed
251.Pp
252The multiplication may lead to an integer overflow.
253To avoid this,
254.Fn calloc
255is recommended.
256.Pp
257If
258.Fn malloc
259must be used, be sure to test for overflow:
260.Bd -literal -offset indent
261if (size && number > SIZE_MAX / size) {
262	errno = EOVERFLOW;
263	err(EXIT_FAILURE, "allocation");
264}
265.Ed
266.Pp
267When using
268.Fn realloc ,
269one must be careful to avoid the following idiom:
270.Bd -literal -offset indent
271nsize += 50;
272
273if ((p = realloc(p, nsize)) == NULL)
274	return NULL;
275.Ed
276.Pp
277Do not adjust the variable describing how much memory has been allocated
278until it is known that the allocation has been successful.
279This can cause aberrant program behavior if the incorrect size value is used.
280In most cases, the above example will also leak memory.
281As stated earlier, a return value of
282.Dv NULL
283indicates that the old object still remains allocated.
284Better code looks like this:
285.Bd -literal -offset indent
286newsize = size + 50;
287
288if ((p2 = realloc(p, newsize)) == NULL) {
289
290	if (p != NULL)
291		free(p);
292
293	p = NULL;
294	return NULL;
295}
296
297p = p2;
298size = newsize;
299.Ed
300.Sh DIAGNOSTICS
301If
302.Fn malloc ,
303.Fn calloc ,
304.Fn realloc
305or
306.Fn free
307detect an error, a message will be printed to file descriptor
308.Dv STDERR_FILENO
309and the process will dump core.
310.Sh SEE ALSO
311.Xr madvise 2 ,
312.Xr mmap 2 ,
313.Xr sbrk 2 ,
314.Xr alloca 3 ,
315.Xr atexit 3 ,
316.Xr emalloc 3 ,
317.Xr getpagesize 3 ,
318.Xr memory 3 ,
319.Xr posix_memalign 3
320.Sh STANDARDS
321The
322.Fn malloc ,
323.Fn calloc ,
324.Fn realloc
325and
326.Fn free
327functions conform to
328.St -isoC .
329.Sh HISTORY
330The
331.Fn reallocf
332function first appeared in
333.Fx 3.0 .
334.Pp
335.Dx Ap s
336.Nm
337implementation is based on the kernel's slab allocator (see
338.Xr posix_memalign 3 Ap s
339.Sx IMPLEMENTATION NOTES ) .
340It first appeared in
341.Dx 2.3 .
342.Sh AUTHORS
343.An Matt Dillon
344