xref: /dragonfly/lib/libc/stdlib/malloc.3 (revision 2e3ed54d)
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. All advertising materials mentioning features or use of this software
17.\"    must display the following acknowledgement:
18.\"	This product includes software developed by the University of
19.\"	California, Berkeley and its contributors.
20.\" 4. Neither the name of the University nor the names of its contributors
21.\"    may be used to endorse or promote products derived from this software
22.\"    without specific prior written permission.
23.\"
24.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34.\" SUCH DAMAGE.
35.\"
36.\"     @(#)malloc.3	8.1 (Berkeley) 6/4/93
37.\" $FreeBSD: src/lib/libc/stdlib/malloc.3,v 1.25.2.16 2003/01/06 17:10:45 trhodes Exp $
38.\" $DragonFly: src/lib/libc/stdlib/malloc.3,v 1.5 2005/08/05 22:35:10 swildner Exp $
39.\"
40.Dd August 27, 1996
41.Dt MALLOC 3
42.Os
43.Sh NAME
44.Nm malloc ,
45.Nm calloc ,
46.Nm realloc ,
47.Nm free ,
48.Nm reallocf
49.Nd general purpose memory allocation functions
50.Sh LIBRARY
51.Lb libc
52.Sh SYNOPSIS
53.In stdlib.h
54.Ft void *
55.Fn malloc "size_t size"
56.Ft void *
57.Fn calloc "size_t number" "size_t size"
58.Ft void *
59.Fn realloc "void *ptr" "size_t size"
60.Ft void *
61.Fn reallocf "void *ptr" "size_t size"
62.Ft void
63.Fn free "void *ptr"
64.Ft char *
65.Va malloc_options;
66.Sh DESCRIPTION
67The
68.Fn malloc
69function allocates
70.Fa size
71bytes of memory.
72The allocated space is suitably aligned (after possible pointer coercion)
73for storage of any type of object.
74If the space is at least
75.Em pagesize
76bytes in length (see
77.Xr getpagesize 3 ) ,
78the returned memory will be page boundary aligned as well.
79If
80.Fn malloc
81fails, a
82.Dv NULL
83pointer is returned.
84.Pp
85Note that
86.Fn malloc
87does
88.Em NOT
89normally initialize the returned memory to zero bytes.
90.Pp
91The
92.Fn calloc
93function allocates space for
94.Fa number
95objects,
96each
97.Fa size
98bytes in length.
99The result is identical to calling
100.Fn malloc
101with an argument of
102.Dq "number * size" ,
103with the exception that the allocated memory is explicitly initialized
104to zero bytes.
105.Pp
106The
107.Fn realloc
108function changes the size of the previously allocated memory referenced by
109.Fa ptr
110to
111.Fa size
112bytes.
113The contents of the memory are unchanged up to the lesser of the new and
114old sizes.
115If the new size is larger,
116the value of the newly allocated portion of the memory is undefined.
117If the requested memory cannot be allocated,
118.Dv NULL
119is returned and
120the memory referenced by
121.Fa ptr
122is valid and unchanged.
123If
124.Fa ptr
125is
126.Dv NULL ,
127the
128.Fn realloc
129function behaves identically to
130.Fn malloc
131for the specified size.
132.Pp
133The
134.Fn reallocf
135function call is identical to the realloc function call, except that it
136will free the passed pointer when the requested memory cannot be allocated.
137This is a
138.Fx
139/
140.Dx
141specific API designed to ease the problems with traditional coding styles
142for realloc causing memory leaks in libraries.
143.Pp
144The
145.Fn free
146function causes the allocated memory referenced by
147.Fa ptr
148to be made available for future allocations.
149If
150.Fa ptr
151is
152.Dv NULL ,
153no action occurs.
154.Sh TUNING
155Once, when the first call is made to one of these memory allocation
156routines, various flags will be set or reset, which affect the
157workings of this allocation implementation.
158.Pp
159The ``name'' of the file referenced by the symbolic link named
160.Pa /etc/malloc.conf ,
161the value of the environment variable
162.Ev MALLOC_OPTIONS ,
163and the string pointed to by the global variable
164.Va malloc_options
165will be interpreted, in that order, character by character as flags.
166.Pp
167Most flags are single letters,
168where uppercase indicates that the behavior is set, or on,
169and lowercase means that the behavior is not set, or off.
170.Bl -tag -width indent
171.It A
172All warnings (except for the warning about unknown
173flags being set) become fatal.
174The process will call
175.Xr abort 3
176in these cases.
177.It J
178Each byte of new memory allocated by
179.Fn malloc ,
180.Fn realloc
181or
182.Fn reallocf
183as well as all memory returned by
184.Fn free ,
185.Fn realloc
186or
187.Fn reallocf
188will be initialized to 0xd0.
189This options also sets the
190.Dq R
191option.
192This is intended for debugging and will impact performance negatively.
193.It H
194Pass a hint to the kernel about pages unused by the allocation functions.
195This will help performance if the system is paging excessively.  This
196option is off by default.
197.It R
198Causes the
199.Fn realloc
200and
201.Fn reallocf
202functions to always reallocate memory even if the initial allocation was
203sufficiently large.
204This can substantially aid in compacting memory.
205.It U
206Generate
207.Dq utrace
208entries for
209.Xr ktrace 1 ,
210for all operations.
211Consult the source for details on this option.
212.It V
213Attempting to allocate zero bytes will return a
214.Dv NULL
215pointer instead of
216a valid pointer.
217(The default behavior is to make a minimal allocation and return a
218pointer to it.)
219This option is provided for System V compatibility.
220This option is incompatible with the
221.Dq X
222option.
223.It X
224Rather than return failure for any allocation function,
225display a diagnostic message on stderr and cause the program to drop
226core (using
227.Xr abort 3 ) .
228This option should be set at compile time by including the following in
229the source code:
230.Bd -literal -offset indent
231extern char *malloc_options;
232malloc_options = "X";
233.Ed
234.It Z
235This option implicitly sets the
236.Dq J
237and
238.Dq R
239options, and then zeros out the bytes that were requested.
240This is intended for debugging and will impact performance negatively.
241.It <
242Reduce the size of the cache by a factor of two.
243The default cache size is 16 pages.
244This option can be specified multiple times.
245.It >
246Double the size of the cache by a factor of two.
247The default cache size is 16 pages.
248This option can be specified multiple times.
249.El
250.Pp
251The
252.Dq J
253and
254.Dq Z
255options are intended for testing and debugging.
256An application which changes its behavior when these options are used
257is flawed.
258.Sh EXAMPLES
259To set a systemwide reduction of cache size, and to dump core whenever
260a problem occurs:
261.Pp
262.Bd -literal -offset indent
263ln -s 'A<' /etc/malloc.conf
264.Ed
265.Pp
266To specify in the source that a program does no return value checking
267on calls to these functions:
268.Bd -literal -offset indent
269extern char *malloc_options;
270malloc_options = "X";
271.Ed
272.Sh ENVIRONMENT
273The following environment variables affect the execution of the allocation
274functions:
275.Bl -tag -width ".Ev MALLOC_OPTIONS"
276.It Ev MALLOC_OPTIONS
277If the environment variable
278.Ev MALLOC_OPTIONS
279is set, the characters it contains will be interpreted as flags to the
280allocation functions.
281.El
282.Sh RETURN VALUES
283The
284.Fn malloc
285and
286.Fn calloc
287functions return a pointer to the allocated memory if successful; otherwise
288a
289.Dv NULL
290pointer is returned and
291.Va errno
292is set to
293.Er ENOMEM .
294.Pp
295The
296.Fn realloc
297and
298.Fn reallocf
299functions return a pointer, possibly identical to
300.Fa ptr ,
301to the allocated memory
302if successful; otherwise a
303.Dv NULL
304pointer is returned, and
305.Va errno
306is set to
307.Er ENOMEM
308if the error was the result of an allocation failure.
309The
310.Fn realloc
311function always leaves the original buffer intact
312when an error occurs, whereas
313.Fn reallocf
314deallocates it in this case.
315.Pp
316The
317.Fn free
318function returns no value.
319.Sh DEBUGGING MALLOC PROBLEMS
320The major difference between this implementation and other allocation
321implementations is that the free pages are not accessed unless allocated,
322and are aggressively returned to the kernel for reuse.
323.Bd -ragged -offset indent
324Most allocation implementations will store a data structure containing a
325linked list in the free chunks of memory,
326used to tie all the free memory together.
327That can be suboptimal,
328as every time the free-list is traversed,
329the otherwise unused, and likely paged out,
330pages are faulted into primary memory.
331On systems which are paging,
332this can result in a factor of five increase in the number of page-faults
333done by a process.
334.Ed
335.Pp
336A side effect of this architecture is that many minor transgressions on
337the interface which would traditionally not be detected are in fact
338detected.  As a result, programs that have been running happily for
339years may suddenly start to complain loudly, when linked with this
340allocation implementation.
341.Pp
342The first and most important thing to do is to set the
343.Dq A
344option.
345This option forces a coredump (if possible) at the first sign of trouble,
346rather than the normal policy of trying to continue if at all possible.
347.Pp
348It is probably also a good idea to recompile the program with suitable
349options and symbols for debugger support.
350.Pp
351If the program starts to give unusual results, coredump or generally behave
352differently without emitting any of the messages listed in the next
353section, it is likely because it depends on the storage being filled with
354zero bytes.  Try running it with
355.Dq Z
356option set;
357if that improves the situation, this diagnosis has been confirmed.
358If the program still misbehaves,
359the likely problem is accessing memory outside the allocated area,
360more likely after than before the allocated area.
361.Pp
362Alternatively, if the symptoms are not easy to reproduce, setting the
363.Dq J
364option may help provoke the problem.
365.Pp
366In truly difficult cases, the
367.Dq U
368option, if supported by the kernel, can provide a detailed trace of
369all calls made to these functions.
370.Pp
371Unfortunately this implementation does not provide much detail about
372the problems it detects, the performance impact for storing such information
373would be prohibitive.
374There are a number of allocation implementations available on the 'Net
375which focus on detecting and pinpointing problems by trading performance
376for extra sanity checks and detailed diagnostics.
377.Sh DIAGNOSTIC MESSAGES
378If
379.Fn malloc ,
380.Fn calloc ,
381.Fn realloc
382or
383.Fn free
384detect an error or warning condition,
385a message will be printed to file descriptor STDERR_FILENO.
386Errors will result in the process dumping core.
387If the
388.Dq A
389option is set, all warnings are treated as errors.
390.Pp
391The following is a brief description of possible error messages and
392their meanings:
393.Pp
394.Bl -diag
395.It "(ES): mumble mumble mumble"
396The allocation functions were compiled with
397.Dq EXTRA_SANITY
398defined, and an error was found during the additional error checking.
399Consult the source code for further information.
400.It "mmap(2) failed, check limits"
401This most likely means that the system is dangerously overloaded or that
402the process' limits are incorrectly specified.
403.It "freelist is destroyed"
404The internal free-list has been corrupted.
405.It "out of memory"
406The
407.Dq X
408option was specified and an allocation of memory failed.
409.El
410.Pp
411The following is a brief description of possible warning messages and
412their meanings:
413.Bl -diag
414.It "chunk/page is already free"
415The process attempted to
416.Fn free
417memory which had already been freed.
418.It "junk pointer, ..."
419A pointer specified to one of the allocation functions points outside the
420bounds of the memory of which they are aware.
421.It "malloc() has never been called"
422No memory has been allocated,
423yet something is being freed or
424realloc'ed.
425.It "modified (chunk-/page-) pointer"
426The pointer passed to
427.Fn free
428or
429.Fn realloc
430has been modified.
431.It "pointer to wrong page"
432The pointer that
433.Fn free ,
434.Fn realloc ,
435or
436.Fn reallocf
437is trying to free does not reference a possible page.
438.It "recursive call"
439A process has attempted to call an allocation function recursively.
440This is not permitted.  In particular, signal handlers should not
441attempt to allocate memory.
442.It "unknown char in MALLOC_OPTIONS"
443An unknown option was specified.
444Even with the
445.Dq A
446option set, this warning is still only a warning.
447.El
448.Sh SEE ALSO
449.Xr brk 2 ,
450.Xr mmap 2 ,
451.Xr alloca 3 ,
452.Xr getpagesize 3 ,
453.Xr memory 3
454.Pa /usr/share/doc/papers/malloc.ascii.gz
455.Sh STANDARDS
456The
457.Fn malloc ,
458.Fn calloc ,
459.Fn realloc
460and
461.Fn free
462functions conform to
463.St -isoC .
464.Sh HISTORY
465The present allocation implementation started out as a filesystem for a
466drum attached to a 20bit binary challenged computer which was built
467with discrete germanium transistors.  It has since graduated to
468handle primary storage rather than secondary.
469It first appeared in its new shape and ability in
470.Fx 2.2 .
471.Pp
472The
473.Fn reallocf
474function first appeared in
475.Fx 3.0 .
476.Sh AUTHORS
477.An Poul-Henning Kamp Aq phk@FreeBSD.org
478.Sh BUGS
479The messages printed in case of problems provide no detail about the
480actual values.
481.Pp
482It can be argued that returning a
483.Dv NULL
484pointer when asked to
485allocate zero bytes is a silly response to a silly question.
486