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