xref: /netbsd-src/lib/libc/stdlib/malloc.3 (revision da9817918ec7e88db2912a2882967c7570a83f47)
1.\" $NetBSD: malloc.3,v 1.29 2009/05/18 09:00:02 wiz 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 October 15, 2007
38.Dt MALLOC 3
39.Os
40.Sh NAME
41.Nm malloc , calloc , realloc , free
42.Nd general purpose memory allocation functions
43.Sh LIBRARY
44.Lb libc
45.Sh SYNOPSIS
46.In stdlib.h
47.Ft void *
48.Fn malloc "size_t size"
49.Ft void *
50.Fn calloc "size_t number" "size_t size"
51.Ft void *
52.Fn realloc "void *ptr" "size_t size"
53.Ft void
54.Fn free "void *ptr"
55.Ft const char *
56.Va _malloc_options ;
57.Sh DESCRIPTION
58The
59.Fn malloc
60function allocates
61.Fa size
62bytes of uninitialized memory.
63The allocated space is suitably aligned (after possible pointer coercion)
64for storage of any type of object.
65.Pp
66The
67.Fn calloc
68function allocates space for
69.Fa number
70objects,
71each
72.Fa size
73bytes in length.
74The result is identical to calling
75.Fn malloc
76with an argument of
77.Dq "number * size" ,
78with the exception that the allocated memory is explicitly initialized
79to zero bytes.
80.Pp
81The
82.Fn realloc
83function changes the size of the previously allocated memory referenced by
84.Fa ptr
85to
86.Fa size
87bytes.
88The contents of the memory are unchanged up to the lesser of the new and
89old sizes.
90If the new size is larger,
91the value of the newly allocated portion of the memory is undefined.
92Upon success, the memory referenced by
93.Fa ptr
94is freed and a pointer to the newly allocated memory is returned.
95Note that
96.Fn realloc
97may move the memory allocation, resulting in a different return value than
98.Fa ptr .
99If
100.Fa ptr
101is
102.Dv NULL ,
103the
104.Fn realloc
105function behaves identically to
106.Fn malloc
107for the specified size.
108.Pp
109The
110.Fn free
111function causes the allocated memory referenced by
112.Fa ptr
113to be made available for future allocations.
114If
115.Fa ptr
116is
117.Dv NULL ,
118no action occurs.
119.Sh TUNING
120Once, when the first call is made to one of these memory allocation
121routines, various flags will be set or reset, which affect the
122workings of this allocator implementation.
123.Pp
124The
125.Dq name
126of the file referenced by the symbolic link named
127.Pa /etc/malloc.conf ,
128the value of the environment variable
129.Ev MALLOC_OPTIONS ,
130and the string pointed to by the global variable
131.Va _malloc_options
132will be interpreted, in that order, character by character as flags.
133.Pp
134Most flags are single letters,
135where uppercase indicates that the behavior is set, or on,
136and lowercase means that the behavior is not set, or off.
137.Bl -tag -width indent
138.It A
139All warnings (except for the warning about unknown
140flags being set) become fatal.
141The process will call
142.Xr abort 3
143in these cases.
144.It H
145Use
146.Xr madvise 2
147when pages within a chunk are no longer in use, but the chunk as a whole cannot
148yet be deallocated.
149This is primarily of use when swapping is a real possibility, due to the high
150overhead of the
151.Fn madvise
152system call.
153.It J
154Each byte of new memory allocated by
155.Fn malloc ,
156.Fn realloc
157will be initialized to 0xa5.
158All memory returned by
159.Fn free ,
160.Fn realloc
161will be initialized to 0x5a.
162This is intended for debugging and will impact performance negatively.
163.It K
164Increase/decrease the virtual memory chunk size by a factor of two.
165The default chunk size is 1 MB.
166This option can be specified multiple times.
167.It N
168Increase/decrease the number of arenas by a factor of two.
169The default number of arenas is four times the number of CPUs, or one if there
170is a single CPU.
171This option can be specified multiple times.
172.It P
173Various statistics are printed at program exit via an
174.Xr atexit 3
175function.
176This has the potential to cause deadlock for a multi-threaded process that exits
177while one or more threads are executing in the memory allocation functions.
178Therefore, this option should only be used with care; it is primarily intended
179as a performance tuning aid during application development.
180.It Q
181Increase/decrease the size of the allocation quantum by a factor of two.
182The default quantum is the minimum allowed by the architecture (typically 8 or
18316 bytes).
184This option can be specified multiple times.
185.It S
186Increase/decrease the size of the maximum size class that is a multiple of the
187quantum by a factor of two.
188Above this size, power-of-two spacing is used for size classes.
189The default value is 512 bytes.
190This option can be specified multiple times.
191.It U
192Generate
193.Dq utrace
194entries for
195.Xr ktrace 1 ,
196for all operations.
197Consult the source for details on this option.
198.It V
199Attempting to allocate zero bytes will return a
200.Dv NULL
201pointer instead of a 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
227does 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 \&: Pq 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