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