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