]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - lib/libc/stdlib/malloc.3
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.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. Neither the name of the University nor the names of its contributors
17 .\"    may be used to endorse or promote products derived from this software
18 .\"    without specific prior written permission.
19 .\"
20 .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 .\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 .\" SUCH DAMAGE.
31 .\"
32 .\"     @(#)malloc.3    8.1 (Berkeley) 6/4/93
33 .\" $FreeBSD$
34 .\"
35 .Dd February 17, 2008
36 .Dt MALLOC 3
37 .Os
38 .Sh NAME
39 .Nm malloc , calloc , realloc , free , reallocf , malloc_usable_size
40 .Nd general purpose memory allocation functions
41 .Sh LIBRARY
42 .Lb libc
43 .Sh SYNOPSIS
44 .In stdlib.h
45 .Ft void *
46 .Fn malloc "size_t size"
47 .Ft void *
48 .Fn calloc "size_t number" "size_t size"
49 .Ft void *
50 .Fn realloc "void *ptr" "size_t size"
51 .Ft void *
52 .Fn reallocf "void *ptr" "size_t size"
53 .Ft void
54 .Fn free "void *ptr"
55 .Ft const char *
56 .Va _malloc_options ;
57 .Ft void
58 .Fo \*(lp*_malloc_message\*(rp
59 .Fa "const char *p1" "const char *p2" "const char *p3" "const char *p4"
60 .Fc
61 .In malloc_np.h
62 .Ft size_t
63 .Fn malloc_usable_size "const void *ptr"
64 .Sh DESCRIPTION
65 The
66 .Fn malloc
67 function allocates
68 .Fa size
69 bytes of uninitialized memory.
70 The allocated space is suitably aligned (after possible pointer coercion)
71 for storage of any type of object.
72 .Pp
73 The
74 .Fn calloc
75 function allocates space for
76 .Fa number
77 objects,
78 each
79 .Fa size
80 bytes in length.
81 The result is identical to calling
82 .Fn malloc
83 with an argument of
84 .Dq "number * size" ,
85 with the exception that the allocated memory is explicitly initialized
86 to zero bytes.
87 .Pp
88 The
89 .Fn realloc
90 function changes the size of the previously allocated memory referenced by
91 .Fa ptr
92 to
93 .Fa size
94 bytes.
95 The contents of the memory are unchanged up to the lesser of the new and
96 old sizes.
97 If the new size is larger,
98 the contents of the newly allocated portion of the memory are undefined.
99 Upon success, the memory referenced by
100 .Fa ptr
101 is freed and a pointer to the newly allocated memory is returned.
102 Note that
103 .Fn realloc
104 and
105 .Fn reallocf
106 may move the memory allocation, resulting in a different return value than
107 .Fa ptr .
108 If
109 .Fa ptr
110 is
111 .Dv NULL ,
112 the
113 .Fn realloc
114 function behaves identically to
115 .Fn malloc
116 for the specified size.
117 .Pp
118 The
119 .Fn reallocf
120 function is identical to the
121 .Fn realloc
122 function, except that it
123 will free the passed pointer when the requested memory cannot be allocated.
124 This is a
125 .Fx
126 specific API designed to ease the problems with traditional coding styles
127 for realloc causing memory leaks in libraries.
128 .Pp
129 The
130 .Fn free
131 function causes the allocated memory referenced by
132 .Fa ptr
133 to be made available for future allocations.
134 If
135 .Fa ptr
136 is
137 .Dv NULL ,
138 no action occurs.
139 .Pp
140 The
141 .Fn malloc_usable_size
142 function returns the usable size of the allocation pointed to by
143 .Fa ptr .
144 The return value may be larger than the size that was requested during
145 allocation.
146 The
147 .Fn malloc_usable_size
148 function is not a mechanism for in-place
149 .Fn realloc ;
150 rather it is provided solely as a tool for introspection purposes.
151 Any discrepancy between the requested allocation size and the size reported by
152 .Fn malloc_usable_size
153 should not be depended on, since such behavior is entirely
154 implementation-dependent.
155 .Sh TUNING
156 Once, when the first call is made to one of these memory allocation
157 routines, various flags will be set or reset, which affect the
158 workings of this allocator implementation.
159 .Pp
160 The
161 .Dq name
162 of the file referenced by the symbolic link named
163 .Pa /etc/malloc.conf ,
164 the value of the environment variable
165 .Ev MALLOC_OPTIONS ,
166 and the string pointed to by the global variable
167 .Va _malloc_options
168 will be interpreted, in that order, from left to right as flags.
169 .Pp
170 Each flag is a single letter, optionally prefixed by a non-negative base 10
171 integer repetition count.
172 For example,
173 .Dq 3N
174 is equivalent to
175 .Dq NNN .
176 Some flags control parameter magnitudes, where uppercase increases the
177 magnitude, and lowercase decreases the magnitude.
178 Other flags control boolean parameters, where uppercase indicates that a
179 behavior is set, or on, and lowercase means that a behavior is not set, or off.
180 .Bl -tag -width indent
181 .It A
182 All warnings (except for the warning about unknown
183 flags being set) become fatal.
184 The process will call
185 .Xr abort 3
186 in these cases.
187 .It B
188 Double/halve the per-arena lock contention threshold at which a thread is
189 randomly re-assigned to an arena.
190 This dynamic load balancing tends to push threads away from highly contended
191 arenas, which avoids worst case contention scenarios in which threads
192 disproportionately utilize arenas.
193 However, due to the highly dynamic load that applications may place on the
194 allocator, it is impossible for the allocator to know in advance how sensitive
195 it should be to contention over arenas.
196 Therefore, some applications may benefit from increasing or decreasing this
197 threshold parameter.
198 This option is not available for some configurations (non-PIC).
199 .It D
200 Use
201 .Xr sbrk 2
202 to acquire memory in the data storage segment (DSS).
203 This option is enabled by default.
204 See the
205 .Dq M
206 option for related information and interactions.
207 .It F
208 Double/halve the per-arena maximum number of dirty unused pages that are
209 allowed to accumulate before informing the kernel about at least half of those
210 pages via
211 .Xr madvise 2 .
212 This provides the kernel with sufficient information to recycle dirty pages if
213 physical memory becomes scarce and the pages remain unused.
214 The default is 512 pages per arena;
215 .Ev MALLOC_OPTIONS=10f
216 will prevent any dirty unused pages from accumulating.
217 .It H
218 Obsoleted by the
219 .Dq F
220 option.
221 .Ev MALLOC_OPTIONS=H
222 sets the per-arena maximum number of dirty unused pages to 0, and
223 .Ev MALLOC_OPTIONS=h
224 resets the per-arena maximum number of dirty unused pages to the default.
225 This option will be removed in
226 .Fx 8.0 .
227 .It J
228 Each byte of new memory allocated by
229 .Fn malloc ,
230 .Fn realloc
231 or
232 .Fn reallocf
233 will be initialized to 0xa5.
234 All memory returned by
235 .Fn free ,
236 .Fn realloc
237 or
238 .Fn reallocf
239 will be initialized to 0x5a.
240 This is intended for debugging and will impact performance negatively.
241 .It K
242 Double/halve the virtual memory chunk size.
243 The default chunk size is 1 MB.
244 .It M
245 Use
246 .Xr mmap 2
247 to acquire anonymously mapped memory.
248 This option is enabled by default.
249 If both the
250 .Dq D
251 and
252 .Dq M
253 options are enabled, the allocator prefers anonymous mappings over the DSS,
254 but allocation only fails if memory cannot be acquired via either method.
255 If neither option is enabled, then the
256 .Dq M
257 option is implicitly enabled in order to assure that there is a method for
258 acquiring memory.
259 .It N
260 Double/halve the number of arenas.
261 The default number of arenas is four times the number of CPUs, or one if there
262 is a single CPU.
263 .It P
264 Various statistics are printed at program exit via an
265 .Xr atexit 3
266 function.
267 This has the potential to cause deadlock for a multi-threaded process that exits
268 while one or more threads are executing in the memory allocation functions.
269 Therefore, this option should only be used with care; it is primarily intended
270 as a performance tuning aid during application development.
271 .It Q
272 Double/halve the size of the allocation quantum.
273 The default quantum is the minimum allowed by the architecture (typically 8 or
274 16 bytes).
275 .It S
276 Double/halve the size of the maximum size class that is a multiple of the
277 quantum.
278 Above this size, power-of-two spacing is used for size classes.
279 The default value is 512 bytes.
280 .It U
281 Generate
282 .Dq utrace
283 entries for
284 .Xr ktrace 1 ,
285 for all operations.
286 Consult the source for details on this option.
287 .It V
288 Attempting to allocate zero bytes will return a
289 .Dv NULL
290 pointer instead of
291 a valid pointer.
292 (The default behavior is to make a minimal allocation and return a
293 pointer to it.)
294 This option is provided for System V compatibility.
295 This option is incompatible with the
296 .Dq X
297 option.
298 .It X
299 Rather than return failure for any allocation function,
300 display a diagnostic message on
301 .Dv stderr
302 and cause the program to drop
303 core (using
304 .Xr abort 3 ) .
305 This option should be set at compile time by including the following in
306 the source code:
307 .Bd -literal -offset indent
308 _malloc_options = "X";
309 .Ed
310 .It Z
311 Each byte of new memory allocated by
312 .Fn malloc ,
313 .Fn realloc
314 or
315 .Fn reallocf
316 will be initialized to 0.
317 Note that this initialization only happens once for each byte, so
318 .Fn realloc
319 and
320 .Fn reallocf
321 calls do not zero memory that was previously allocated.
322 This is intended for debugging and will impact performance negatively.
323 .El
324 .Pp
325 The
326 .Dq J
327 and
328 .Dq Z
329 options are intended for testing and debugging.
330 An application which changes its behavior when these options are used
331 is flawed.
332 .Sh IMPLEMENTATION NOTES
333 Traditionally, allocators have used
334 .Xr sbrk 2
335 to obtain memory, which is suboptimal for several reasons, including race
336 conditions, increased fragmentation, and artificial limitations on maximum
337 usable memory.
338 This allocator uses both
339 .Xr sbrk 2
340 and
341 .Xr mmap 2
342 by default, but it can be configured at run time to use only one or the other.
343 If resource limits are not a primary concern, the preferred configuration is
344 .Ev MALLOC_OPTIONS=dM
345 or
346 .Ev MALLOC_OPTIONS=DM .
347 When so configured, the
348 .Ar datasize
349 resource limit has little practical effect for typical applications; use
350 .Ev MALLOC_OPTIONS=Dm
351 if that is a concern.
352 Regardless of allocator configuration, the
353 .Ar vmemoryuse
354 resource limit can be used to bound the total virtual memory used by a
355 process, as described in
356 .Xr limits 1 .
357 .Pp
358 This allocator uses multiple arenas in order to reduce lock contention for
359 threaded programs on multi-processor systems.
360 This works well with regard to threading scalability, but incurs some costs.
361 There is a small fixed per-arena overhead, and additionally, arenas manage
362 memory completely independently of each other, which means a small fixed
363 increase in overall memory fragmentation.
364 These overheads are not generally an issue, given the number of arenas normally
365 used.
366 Note that using substantially more arenas than the default is not likely to
367 improve performance, mainly due to reduced cache performance.
368 However, it may make sense to reduce the number of arenas if an application
369 does not make much use of the allocation functions.
370 .Pp
371 Memory is conceptually broken into equal-sized chunks, where the chunk size is
372 a power of two that is greater than the page size.
373 Chunks are always aligned to multiples of the chunk size.
374 This alignment makes it possible to find metadata for user objects very
375 quickly.
376 .Pp
377 User objects are broken into three categories according to size: small, large,
378 and huge.
379 Small objects are no larger than one half of a page.
380 Large objects are smaller than the chunk size.
381 Huge objects are a multiple of the chunk size.
382 Small and large objects are managed by arenas; huge objects are managed
383 separately in a single data structure that is shared by all threads.
384 Huge objects are used by applications infrequently enough that this single
385 data structure is not a scalability issue.
386 .Pp
387 Each chunk that is managed by an arena tracks its contents as runs of
388 contiguous pages (unused, backing a set of small objects, or backing one large
389 object).
390 The combination of chunk alignment and chunk page maps makes it possible to
391 determine all metadata regarding small and large allocations in
392 constant and logarithmic time, respectively.
393 .Pp
394 Small objects are managed in groups by page runs.
395 Each run maintains a bitmap that tracks which regions are in use.
396 Allocation requests that are no more than half the quantum (see the
397 .Dq Q
398 option) are rounded up to the nearest power of two (typically 2, 4, or 8).
399 Allocation requests that are more than half the quantum, but no more than the
400 maximum quantum-multiple size class (see the
401 .Dq S
402 option) are rounded up to the nearest multiple of the quantum.
403 Allocation requests that are larger than the maximum quantum-multiple size
404 class, but no larger than one half of a page, are rounded up to the nearest
405 power of two.
406 Allocation requests that are larger than half of a page, but small enough to
407 fit in an arena-managed chunk (see the
408 .Dq K
409 option), are rounded up to the nearest run size.
410 Allocation requests that are too large to fit in an arena-managed chunk are
411 rounded up to the nearest multiple of the chunk size.
412 .Pp
413 Allocations are packed tightly together, which can be an issue for
414 multi-threaded applications.
415 If you need to assure that allocations do not suffer from cache line sharing,
416 round your allocation requests up to the nearest multiple of the cache line
417 size.
418 .Sh DEBUGGING MALLOC PROBLEMS
419 The first thing to do is to set the
420 .Dq A
421 option.
422 This option forces a coredump (if possible) at the first sign of trouble,
423 rather than the normal policy of trying to continue if at all possible.
424 .Pp
425 It is probably also a good idea to recompile the program with suitable
426 options and symbols for debugger support.
427 .Pp
428 If the program starts to give unusual results, coredump or generally behave
429 differently without emitting any of the messages mentioned in the next
430 section, it is likely because it depends on the storage being filled with
431 zero bytes.
432 Try running it with the
433 .Dq Z
434 option set;
435 if that improves the situation, this diagnosis has been confirmed.
436 If the program still misbehaves,
437 the likely problem is accessing memory outside the allocated area.
438 .Pp
439 Alternatively, if the symptoms are not easy to reproduce, setting the
440 .Dq J
441 option may help provoke the problem.
442 .Pp
443 In truly difficult cases, the
444 .Dq U
445 option, if supported by the kernel, can provide a detailed trace of
446 all calls made to these functions.
447 .Pp
448 Unfortunately this implementation does not provide much detail about
449 the problems it detects; the performance impact for storing such information
450 would be prohibitive.
451 There are a number of allocator implementations available on the Internet
452 which focus on detecting and pinpointing problems by trading performance for
453 extra sanity checks and detailed diagnostics.
454 .Sh DIAGNOSTIC MESSAGES
455 If any of the memory allocation/deallocation functions detect an error or
456 warning condition, a message will be printed to file descriptor
457 .Dv STDERR_FILENO .
458 Errors will result in the process dumping core.
459 If the
460 .Dq A
461 option is set, all warnings are treated as errors.
462 .Pp
463 The
464 .Va _malloc_message
465 variable allows the programmer to override the function which emits
466 the text strings forming the errors and warnings if for some reason
467 the
468 .Dv stderr
469 file descriptor is not suitable for this.
470 Please note that doing anything which tries to allocate memory in
471 this function is likely to result in a crash or deadlock.
472 .Pp
473 All messages are prefixed by
474 .Dq Ao Ar progname Ac Ns Li : (malloc) .
475 .Sh RETURN VALUES
476 The
477 .Fn malloc
478 and
479 .Fn calloc
480 functions return a pointer to the allocated memory if successful; otherwise
481 a
482 .Dv NULL
483 pointer is returned and
484 .Va errno
485 is set to
486 .Er ENOMEM .
487 .Pp
488 The
489 .Fn realloc
490 and
491 .Fn reallocf
492 functions return a pointer, possibly identical to
493 .Fa ptr ,
494 to the allocated memory
495 if successful; otherwise a
496 .Dv NULL
497 pointer is returned, and
498 .Va errno
499 is set to
500 .Er ENOMEM
501 if the error was the result of an allocation failure.
502 The
503 .Fn realloc
504 function always leaves the original buffer intact
505 when an error occurs, whereas
506 .Fn reallocf
507 deallocates it in this case.
508 .Pp
509 The
510 .Fn free
511 function returns no value.
512 .Pp
513 The
514 .Fn malloc_usable_size
515 function returns the usable size of the allocation pointed to by
516 .Fa ptr .
517 .Sh ENVIRONMENT
518 The following environment variables affect the execution of the allocation
519 functions:
520 .Bl -tag -width ".Ev MALLOC_OPTIONS"
521 .It Ev MALLOC_OPTIONS
522 If the environment variable
523 .Ev MALLOC_OPTIONS
524 is set, the characters it contains will be interpreted as flags to the
525 allocation functions.
526 .El
527 .Sh EXAMPLES
528 To dump core whenever a problem occurs:
529 .Pp
530 .Bd -literal -offset indent
531 ln -s 'A' /etc/malloc.conf
532 .Ed
533 .Pp
534 To specify in the source that a program does no return value checking
535 on calls to these functions:
536 .Bd -literal -offset indent
537 _malloc_options = "X";
538 .Ed
539 .Sh SEE ALSO
540 .Xr limits 1 ,
541 .Xr madvise 2 ,
542 .Xr mmap 2 ,
543 .Xr sbrk 2 ,
544 .Xr alloca 3 ,
545 .Xr atexit 3 ,
546 .Xr getpagesize 3 ,
547 .Xr memory 3 ,
548 .Xr posix_memalign 3
549 .Sh STANDARDS
550 The
551 .Fn malloc ,
552 .Fn calloc ,
553 .Fn realloc
554 and
555 .Fn free
556 functions conform to
557 .St -isoC .
558 .Sh HISTORY
559 The
560 .Fn reallocf
561 function first appeared in
562 .Fx 3.0 .
563 .Pp
564 The
565 .Fn malloc_usable_size
566 function first appeared in
567 .Fx 7.0 .