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