xref: /netbsd-src/lib/libc/stdlib/malloc.3 (revision 8b0f9554ff8762542c4defc4f70e1eb76fb508fa)
1.\" Copyright (c) 1980, 1991, 1993
2.\"	The Regents of the University of California.  All rights reserved.
3.\"
4.\" This code is derived from software contributed to Berkeley by
5.\" the American National Standards Committee X3, on Information
6.\" Processing Systems.
7.\"
8.\" Redistribution and use in source and binary forms, with or without
9.\" modification, are permitted provided that the following conditions
10.\" are met:
11.\" 1. Redistributions of source code must retain the above copyright
12.\"    notice, this list of conditions and the following disclaimer.
13.\" 2. Redistributions in binary form must reproduce the above copyright
14.\"    notice, this list of conditions and the following disclaimer in the
15.\"    documentation and/or other materials provided with the distribution.
16.\" 3. Neither the name of the University nor the names of its contributors
17.\"    may be used to endorse or promote products derived from this software
18.\"    without specific prior written permission.
19.\"
20.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30.\" SUCH DAMAGE.
31.\"
32.\"     @(#)malloc.3	8.1 (Berkeley) 6/4/93
33.\" $FreeBSD: src/lib/libc/stdlib/malloc.3,v 1.73 2007/06/15 22:32:33 jasone Exp $
34.\"
35.Dd October 15, 2007
36.Dt MALLOC 3
37.Os
38.Sh NAME
39.Nm malloc , calloc , realloc , free
40.Nd general purpose memory allocation functions
41.Sh LIBRARY
42.Lb libc
43.Sh SYNOPSIS
44.In stdlib.h
45.Ft void *
46.Fn malloc "size_t size"
47.Ft void *
48.Fn calloc "size_t number" "size_t size"
49.Ft void *
50.Fn realloc "void *ptr" "size_t size"
51.Ft void
52.Fn free "void *ptr"
53.Ft const char *
54.Va _malloc_options ;
55.Sh DESCRIPTION
56The
57.Fn malloc
58function allocates
59.Fa size
60bytes of uninitialized memory.
61The allocated space is suitably aligned (after possible pointer coercion)
62for storage of any type of object.
63.Pp
64The
65.Fn calloc
66function allocates space for
67.Fa number
68objects,
69each
70.Fa size
71bytes in length.
72The result is identical to calling
73.Fn malloc
74with an argument of
75.Dq "number * size" ,
76with the exception that the allocated memory is explicitly initialized
77to zero bytes.
78.Pp
79The
80.Fn realloc
81function changes the size of the previously allocated memory referenced by
82.Fa ptr
83to
84.Fa size
85bytes.
86The contents of the memory are unchanged up to the lesser of the new and
87old sizes.
88If the new size is larger,
89the value of the newly allocated portion of the memory is undefined.
90Upon success, the memory referenced by
91.Fa ptr
92is freed and a pointer to the newly allocated memory is returned.
93Note that
94.Fn realloc
95may move the memory allocation, resulting in a different return value than
96.Fa ptr .
97If
98.Fa ptr
99is
100.Dv NULL ,
101the
102.Fn realloc
103function behaves identically to
104.Fn malloc
105for the specified size.
106.Pp
107The
108.Fn free
109function causes the allocated memory referenced by
110.Fa ptr
111to be made available for future allocations.
112If
113.Fa ptr
114is
115.Dv NULL ,
116no action occurs.
117.Pp
118.Sh TUNING
119Once, when the first call is made to one of these memory allocation
120routines, various flags will be set or reset, which affect the
121workings of this allocator implementation.
122.Pp
123The
124.Dq name
125of the file referenced by the symbolic link named
126.Pa /etc/malloc.conf ,
127the value of the environment variable
128.Ev MALLOC_OPTIONS ,
129and the string pointed to by the global variable
130.Va _malloc_options
131will be interpreted, in that order, character by character as flags.
132.Pp
133Most flags are single letters,
134where uppercase indicates that the behavior is set, or on,
135and lowercase means that the behavior is not set, or off.
136.Bl -tag -width indent
137.It A
138All warnings (except for the warning about unknown
139flags being set) become fatal.
140The process will call
141.Xr abort 3
142in these cases.
143.It H
144Use
145.Xr madvise 2
146when pages within a chunk are no longer in use, but the chunk as a whole cannot
147yet be deallocated.
148This is primarily of use when swapping is a real possibility, due to the high
149overhead of the
150.Fn madvise
151system call.
152.It J
153Each byte of new memory allocated by
154.Fn malloc ,
155.Fn realloc
156will be initialized to 0xa5.
157All memory returned by
158.Fn free ,
159.Fn realloc
160will be initialized to 0x5a.
161This is intended for debugging and will impact performance negatively.
162.It K
163Increase/decrease the virtual memory chunk size by a factor of two.
164The default chunk size is 1 MB.
165This option can be specified multiple times.
166.It N
167Increase/decrease the number of arenas by a factor of two.
168The default number of arenas is four times the number of CPUs, or one if there
169is a single CPU.
170This option can be specified multiple times.
171.It P
172Various statistics are printed at program exit via an
173.Xr atexit 3
174function.
175This has the potential to cause deadlock for a multi-threaded process that exits
176while one or more threads are executing in the memory allocation functions.
177Therefore, this option should only be used with care; it is primarily intended
178as a performance tuning aid during application development.
179.It Q
180Increase/decrease the size of the allocation quantum by a factor of two.
181The default quantum is the minimum allowed by the architecture (typically 8 or
18216 bytes).
183This option can be specified multiple times.
184.It S
185Increase/decrease the size of the maximum size class that is a multiple of the
186quantum by a factor of two.
187Above this size, power-of-two spacing is used for size classes.
188The default value is 512 bytes.
189This option can be specified multiple times.
190.It U
191Generate
192.Dq utrace
193entries for
194.Xr ktrace 1 ,
195for all operations.
196Consult the source for details on this option.
197.It V
198Attempting to allocate zero bytes will return a
199.Dv NULL
200pointer instead of
201a valid pointer.
202(The default behavior is to make a minimal allocation and return a
203pointer to it.)
204This option is provided for System V compatibility.
205This option is incompatible with the
206.Dq X
207option.
208.It X
209Rather than return failure for any allocation function,
210display a diagnostic message on
211.Dv stderr
212and cause the program to drop
213core (using
214.Xr abort 3 ) .
215This option should be set at compile time by including the following in
216the source code:
217.Bd -literal -offset indent
218_malloc_options = "X";
219.Ed
220.It Z
221Each byte of new memory allocated by
222.Fn malloc ,
223.Fn realloc
224will be initialized to 0.
225Note that this initialization only happens once for each byte, so
226.Fn realloc
227call do not zero memory that was previously allocated.
228This is intended for debugging and will impact performance negatively.
229.El
230.Pp
231The
232.Dq J
233and
234.Dq Z
235options are intended for testing and debugging.
236An application which changes its behavior when these options are used
237is flawed.
238.Sh IMPLEMENTATION NOTES
239This allocator uses multiple arenas in order to reduce lock contention for
240threaded programs on multi-processor systems.
241This works well with regard to threading scalability, but incurs some costs.
242There is a small fixed per-arena overhead, and additionally, arenas manage
243memory completely independently of each other, which means a small fixed
244increase in overall memory fragmentation.
245These overheads are not generally an issue, given the number of arenas normally
246used.
247Note that using substantially more arenas than the default is not likely to
248improve performance, mainly due to reduced cache performance.
249However, it may make sense to reduce the number of arenas if an application
250does not make much use of the allocation functions.
251.Pp
252Memory is conceptually broken into equal-sized chunks, where the chunk size is
253a power of two that is greater than the page size.
254Chunks are always aligned to multiples of the chunk size.
255This alignment makes it possible to find metadata for user objects very
256quickly.
257.Pp
258User objects are broken into three categories according to size: small, large,
259and huge.
260Small objects are no larger than one half of a page.
261Large objects are smaller than the chunk size.
262Huge objects are a multiple of the chunk size.
263Small and large objects are managed by arenas; huge objects are managed
264separately in a single data structure that is shared by all threads.
265Huge objects are used by applications infrequently enough that this single
266data structure is not a scalability issue.
267.Pp
268Each chunk that is managed by an arena tracks its contents in a page map as
269runs of contiguous pages (unused, backing a set of small objects, or backing
270one large object).
271The combination of chunk alignment and chunk page maps makes it possible to
272determine all metadata regarding small and large allocations in constant time.
273.Pp
274Small objects are managed in groups by page runs.
275Each run maintains a bitmap that tracks which regions are in use.
276Allocation requests that are no more than half the quantum (see the
277.Dq Q
278option) are rounded up to the nearest power of two (typically 2, 4, or 8).
279Allocation requests that are more than half the quantum, but no more than the
280maximum quantum-multiple size class (see the
281.Dq S
282option) are rounded up to the nearest multiple of the quantum.
283Allocation requests that are larger than the maximum quantum-multiple size
284class, but no larger than one half of a page, are rounded up to the nearest
285power of two.
286Allocation requests that are larger than half of a page, but small enough to
287fit in an arena-managed chunk (see the
288.Dq K
289option), are rounded up to the nearest run size.
290Allocation requests that are too large to fit in an arena-managed chunk are
291rounded up to the nearest multiple of the chunk size.
292.Pp
293Allocations are packed tightly together, which can be an issue for
294multi-threaded applications.
295If you need to assure that allocations do not suffer from cache line sharing,
296round your allocation requests up to the nearest multiple of the cache line
297size.
298.Sh DEBUGGING MALLOC PROBLEMS
299The first thing to do is to set the
300.Dq A
301option.
302This option forces a coredump (if possible) at the first sign of trouble,
303rather than the normal policy of trying to continue if at all possible.
304.Pp
305It is probably also a good idea to recompile the program with suitable
306options and symbols for debugger support.
307.Pp
308If the program starts to give unusual results, coredump or generally behave
309differently without emitting any of the messages mentioned in the next
310section, it is likely because it depends on the storage being filled with
311zero bytes.
312Try running it with the
313.Dq Z
314option set;
315if that improves the situation, this diagnosis has been confirmed.
316If the program still misbehaves,
317the likely problem is accessing memory outside the allocated area.
318.Pp
319Alternatively, if the symptoms are not easy to reproduce, setting the
320.Dq J
321option may help provoke the problem.
322.Pp
323In truly difficult cases, the
324.Dq U
325option, if supported by the kernel, can provide a detailed trace of
326all calls made to these functions.
327.Pp
328Unfortunately this implementation does not provide much detail about
329the problems it detects; the performance impact for storing such information
330would be prohibitive.
331There are a number of allocator implementations available on the Internet
332which focus on detecting and pinpointing problems by trading performance for
333extra sanity checks and detailed diagnostics.
334.Sh DIAGNOSTIC MESSAGES
335If any of the memory allocation/deallocation functions detect an error or
336warning condition, a message will be printed to file descriptor
337.Dv STDERR_FILENO .
338Errors will result in the process dumping core.
339If the
340.Dq A
341option is set, all warnings are treated as errors.
342.Pp
343The
344.Va _malloc_message
345variable allows the programmer to override the function which emits
346the text strings forming the errors and warnings if for some reason
347the
348.Dv stderr
349file descriptor is not suitable for this.
350Please note that doing anything which tries to allocate memory in
351this function is likely to result in a crash or deadlock.
352.Pp
353All messages are prefixed by
354.Dq Ao Ar progname Ac Ns Li : (malloc) .
355.Sh RETURN VALUES
356The
357.Fn malloc
358and
359.Fn calloc
360functions return a pointer to the allocated memory if successful; otherwise
361a
362.Dv NULL
363pointer is returned and
364.Va errno
365is set to
366.Er ENOMEM .
367.Pp
368The
369.Fn realloc
370function returns a pointer, possibly identical to
371.Fa ptr ,
372to the allocated memory
373if successful; otherwise a
374.Dv NULL
375pointer is returned, and
376.Va errno
377is set to
378.Er ENOMEM
379if the error was the result of an allocation failure.
380The
381.Fn realloc
382function always leaves the original buffer intact
383when an error occurs.
384.Pp
385The
386.Fn free
387function returns no value.
388.Sh ENVIRONMENT
389The following environment variables affect the execution of the allocation
390functions:
391.Bl -tag -width ".Ev MALLOC_OPTIONS"
392.It Ev MALLOC_OPTIONS
393If the environment variable
394.Ev MALLOC_OPTIONS
395is set, the characters it contains will be interpreted as flags to the
396allocation functions.
397.El
398.Sh EXAMPLES
399To dump core whenever a problem occurs:
400.Pp
401.Bd -literal -offset indent
402ln -s 'A' /etc/malloc.conf
403.Ed
404.Pp
405To specify in the source that a program does no return value checking
406on calls to these functions:
407.Bd -literal -offset indent
408_malloc_options = "X";
409.Ed
410.Sh SEE ALSO
411.Xr limits 1 ,
412.Xr madvise 2 ,
413.Xr mmap 2 ,
414.Xr sbrk 2 ,
415.Xr alloca 3 ,
416.Xr atexit 3 ,
417.Xr getpagesize 3 ,
418.Xr memory 3 ,
419.Xr posix_memalign 3
420.Sh STANDARDS
421The
422.Fn malloc ,
423.Fn calloc ,
424.Fn realloc
425and
426.Fn free
427functions conform to
428.St -isoC .
429