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