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