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