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