xref: /netbsd/lib/libc/stdlib/malloc.3 (revision bf9ec67e)
1.\"	$NetBSD: malloc.3,v 1.15 2002/02/07 07:00:29 ross 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 \*[Lt]stdlib.h\*[Gt]
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, and the errno variable is
84set to ENOMEM.
85.Pp
86The
87.Fn calloc
88function allocates space for
89.Fa number
90objects,
91each
92.Fa size
93bytes in length.
94The result is identical to calling
95.Fn malloc
96with an argument of
97.Dq "number * size" ,
98with the exception that the allocated memory is initialized to all bits zero.
99.Pp
100The
101.Fn realloc
102function changes the size of the previously allocated memory referenced by
103.Fa ptr
104to
105.Fa size
106bytes.
107The contents of the memory are unchanged up to the lesser of the new and
108old sizes.
109If the new size is larger,
110the value of the newly allocated portion of the memory is undefined.
111If the requested memory cannot be allocated, NULL is returned and
112the memory referenced by
113.Fa ptr
114is valid and unchanged.
115If
116.Fa ptr
117is NULL, the
118.Fn realloc
119function behaves identically to
120.Fn malloc
121for the specified size.
122.\"XXX".Pp
123.\"XXX"The
124.\"XXX".Fn reallocf
125.\"XXX"function call is identical to the realloc function call, except that it
126.\"XXX"will free the passed pointer when the requested memory cannot be allocated.
127.\"XXX"This is a FreeBSD
128.\"XXX"specific API designed to ease the problems with traditional coding styles
129.\"XXX"for realloc causing memory leaks in libraries.
130.Pp
131The
132.Fn free
133function causes the allocated memory referenced by
134.Fa ptr
135to be made available for future allocations.
136If
137.Fa ptr
138is NULL, no action occurs.
139.Sh TUNING
140Once, when the first call is made to one of these memory allocation
141routines, various flags will be set or reset, which affect the
142workings of this allocation implementation.
143.Pp
144The ``name'' of the file referenced by the symbolic link named
145.Pa /etc/malloc.conf ,
146the value of the environment variable
147.Ev MALLOC_OPTIONS ,
148and the string pointed to by the global variable
149.Va malloc_options
150will be interpreted, in that order, character by character as flags.
151.Pp
152Most flags are single letters,
153where uppercase indicates that the behavior is set, or on,
154and lowercase means that the behavior is not set, or off.
155.Bl -tag -width indent
156.It A
157All warnings (except for the warning about unknown
158flags being set), and failure to allocate memory become fatal.
159The process will call
160.Fn abort 3
161in these cases.
162.It J
163Each byte of new memory allocated by
164.\"XXX".Fn malloc ,
165.\"XXX".Fn realloc
166.\"XXX"or
167.\"XXX".Fn reallocf
168.Fn malloc
169or
170.Fn realloc
171as well as all memory returned by
172.\"XXX".Fn free ,
173.\"XXX".Fn realloc
174.\"XXX"or
175.\"XXX"Fn reallocf
176.Fn free
177or
178.Fn realloc
179will be initialized to 0xd0.
180This options also sets the
181.Dq R
182option.
183This is intended for debugging and will impact performance negatively.
184.It H
185Pass a hint to the kernel about pages unused by the allocation functions.
186This will help performance if the system is paging excessively.  This
187option is off by default.
188.It R
189Causes the
190.Fn realloc
191.\"XXX"and
192.\"XXX".Fn reallocf
193.\"XXX"functions
194function
195to always reallocate memory even if the initial allocation was
196sufficiently large.
197This can substantially aid in compacting memory.
198.It U
199Generate
200.Dq utrace
201entries for
202.Xr ktrace 1 ,
203for all operations.
204Consult the source for details on this option.
205.It V
206Attempting to allocate zero bytes will return a NULL pointer instead of
207a valid pointer.
208(The default behavior is to make a minimal allocation and return a
209pointer to it.)
210This option is provided for System V compatibility.
211.It X
212Rather than return failure for any allocation function,
213display a diagnostic message on stderr and cause the program to drop
214core (using
215.Fn abort 3 ) .
216This option should be set at compile time by including the following in
217the source code:
218.Bd -literal -offset indent
219extern char *malloc_options;
220malloc_options = "X";
221.Ed
222.It Z
223This option implicitly sets the
224.Dq J
225and
226.Dq R
227options, and then zeros out the bytes that were requested.
228This is intended for debugging and will impact performance negatively.
229.It \*[Lt]
230Reduce the size of the cache by a factor of two.
231The default cache size is 16 pages.
232This option can be specified multiple times.
233.It \*[Gt]
234Double the size of the cache by a factor of two.
235The default cache size is 16 pages.
236This option can be specified multiple times.
237.El
238.Pp
239The
240.Dq J
241and
242.Dq Z
243options are intended for testing and debugging.
244An application which changes its behavior when these options are used
245is flawed.
246.Sh RETURN VALUES
247The
248.Fn malloc
249and
250.Fn calloc
251functions return a pointer to the allocated memory if successful; otherwise
252a NULL pointer is returned.
253.Pp
254The
255.Fn realloc
256.\"XXX"and
257.\"XXX".Fn reallocf
258.\"XXX"functions return
259function returns
260a pointer, possibly identical to
261.Fa ptr ,
262to the allocated memory
263if successful; otherwise a NULL pointer is returned, in which case the
264memory referenced by
265.Fa ptr
266is still available and intact.
267.Pp
268The
269.Fn free
270function returns no value.
271.Sh ENVIRONMENT
272The following environment variables affect the execution of the allocation
273functions:
274.Bl -tag -width MMM
275.It Ev MALLOC_OPTIONS
276If the environment variable
277.Ev MALLOC_OPTIONS
278is set, the characters it contains will be interpreted as flags to the
279allocation functions.
280.El
281.Sh EXAMPLES
282To set a systemwide reduction of cache size, and to dump core whenever
283a problem occurs:
284.Pp
285.Bd -literal -offset indent
286ln -s 'A\*[Lt]' /etc/malloc.conf
287.Ed
288.Pp
289To specify in the source that a program does no return value checking
290on calls to these functions:
291.Bd -literal -offset indent
292extern char *malloc_options;
293malloc_options = "X";
294.Ed
295.Sh DEBUGGING MALLOC PROBLEMS
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 HISTORY
444The present allocation implementation started out as a filesystem for a
445drum attached to a 20bit binary challenged computer which was built
446with discrete germanium transistors.  It has since graduated to
447handle primary storage rather than secondary.
448It first appeared in its new shape and ability in
449.Fx 2.2 , and then in
450.Nx 1.5 .
451.Sh BUGS
452The messages printed in case of problems provide no detail about the
453actual values.
454.Pp
455It can be argued that returning a null pointer when asked to
456allocate zero bytes is a silly response to a silly question.
457.Pp
458This implementation was authored by Poul-Henning Kamp.
459Please report any problems to him at
460.Aq phk@FreeBSD.org .
461