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