]> CyberLeo.Net >> Repos - FreeBSD/releng/8.1.git/blob - lib/libc/stdlib/malloc.3
Copy stable/8 to releng/8.1 in preparation for 8.1-RC1.
[FreeBSD/releng/8.1.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 September 26, 2009
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 affects 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 C
200 Double/halve the size of the maximum size class that is a multiple of the
201 cacheline size (64).
202 Above this size, subpage spacing (256 bytes) is used for size classes.
203 The default value is 512 bytes.
204 .It D
205 Use
206 .Xr sbrk 2
207 to acquire memory in the data storage segment (DSS).
208 This option is enabled by default.
209 See the
210 .Dq M
211 option for related information and interactions.
212 .It F
213 Double/halve the per-arena maximum number of dirty unused pages that are
214 allowed to accumulate before informing the kernel about at least half of those
215 pages via
216 .Xr madvise 2 .
217 This provides the kernel with sufficient information to recycle dirty pages if
218 physical memory becomes scarce and the pages remain unused.
219 The default is 512 pages per arena;
220 .Ev MALLOC_OPTIONS=10f
221 will prevent any dirty unused pages from accumulating.
222 .It G
223 When there are multiple threads, use thread-specific caching for objects that
224 are smaller than one page.
225 This option is enabled by default.
226 Thread-specific caching allows many allocations to be satisfied without
227 performing any thread synchronization, at the cost of increased memory use.
228 See the
229 .Dq R
230 option for related tuning information.
231 This option is not available for some configurations (non-PIC).
232 .It J
233 Each byte of new memory allocated by
234 .Fn malloc ,
235 .Fn realloc
236 or
237 .Fn reallocf
238 will be initialized to 0xa5.
239 All memory returned by
240 .Fn free ,
241 .Fn realloc
242 or
243 .Fn reallocf
244 will be initialized to 0x5a.
245 This is intended for debugging and will impact performance negatively.
246 .It K
247 Double/halve the virtual memory chunk size.
248 The default chunk size is the maximum of 1 MB and the largest
249 page size that is less than or equal to 4 MB.
250 .It M
251 Use
252 .Xr mmap 2
253 to acquire anonymously mapped memory.
254 This option is enabled by default.
255 If both the
256 .Dq D
257 and
258 .Dq M
259 options are enabled, the allocator prefers anonymous mappings over the DSS,
260 but allocation only fails if memory cannot be acquired via either method.
261 If neither option is enabled, then the
262 .Dq M
263 option is implicitly enabled in order to assure that there is a method for
264 acquiring memory.
265 .It N
266 Double/halve the number of arenas.
267 The default number of arenas is two times the number of CPUs, or one if there
268 is a single CPU.
269 .It P
270 Various statistics are printed at program exit via an
271 .Xr atexit 3
272 function.
273 This has the potential to cause deadlock for a multi-threaded process that exits
274 while one or more threads are executing in the memory allocation functions.
275 Therefore, this option should only be used with care; it is primarily intended
276 as a performance tuning aid during application development.
277 .It Q
278 Double/halve the size of the maximum size class that is a multiple of the
279 quantum (8 or 16 bytes, depending on architecture).
280 Above this size, cacheline spacing is used for size classes.
281 The default value is 128 bytes.
282 .It R
283 Double/halve magazine size, which approximately doubles/halves the number of
284 rounds in each magazine.
285 Magazines are used by the thread-specific caching machinery to acquire and
286 release objects in bulk.
287 Increasing the magazine size decreases locking overhead, at the expense of
288 increased memory usage.
289 This option is not available for some configurations (non-PIC).
290 .It U
291 Generate
292 .Dq utrace
293 entries for
294 .Xr ktrace 1 ,
295 for all operations.
296 Consult the source for details on this option.
297 .It V
298 Attempting to allocate zero bytes will return a
299 .Dv NULL
300 pointer instead of
301 a valid pointer.
302 (The default behavior is to make a minimal allocation and return a
303 pointer to it.)
304 This option is provided for System V compatibility.
305 This option is incompatible with the
306 .Dq X
307 option.
308 .It X
309 Rather than return failure for any allocation function,
310 display a diagnostic message on
311 .Dv stderr
312 and cause the program to drop
313 core (using
314 .Xr abort 3 ) .
315 This option should be set at compile time by including the following in
316 the source code:
317 .Bd -literal -offset indent
318 _malloc_options = "X";
319 .Ed
320 .It Z
321 Each byte of new memory allocated by
322 .Fn malloc ,
323 .Fn realloc
324 or
325 .Fn reallocf
326 will be initialized to 0.
327 Note that this initialization only happens once for each byte, so
328 .Fn realloc
329 and
330 .Fn reallocf
331 calls do not zero memory that was previously allocated.
332 This is intended for debugging and will impact performance negatively.
333 .El
334 .Pp
335 The
336 .Dq J
337 and
338 .Dq Z
339 options are intended for testing and debugging.
340 An application which changes its behavior when these options are used
341 is flawed.
342 .Sh IMPLEMENTATION NOTES
343 Traditionally, allocators have used
344 .Xr sbrk 2
345 to obtain memory, which is suboptimal for several reasons, including race
346 conditions, increased fragmentation, and artificial limitations on maximum
347 usable memory.
348 This allocator uses both
349 .Xr sbrk 2
350 and
351 .Xr mmap 2
352 by default, but it can be configured at run time to use only one or the other.
353 If resource limits are not a primary concern, the preferred configuration is
354 .Ev MALLOC_OPTIONS=dM
355 or
356 .Ev MALLOC_OPTIONS=DM .
357 When so configured, the
358 .Ar datasize
359 resource limit has little practical effect for typical applications; use
360 .Ev MALLOC_OPTIONS=Dm
361 if that is a concern.
362 Regardless of allocator configuration, the
363 .Ar vmemoryuse
364 resource limit can be used to bound the total virtual memory used by a
365 process, as described in
366 .Xr limits 1 .
367 .Pp
368 This allocator uses multiple arenas in order to reduce lock contention for
369 threaded programs on multi-processor systems.
370 This works well with regard to threading scalability, but incurs some costs.
371 There is a small fixed per-arena overhead, and additionally, arenas manage
372 memory completely independently of each other, which means a small fixed
373 increase in overall memory fragmentation.
374 These overheads are not generally an issue, given the number of arenas normally
375 used.
376 Note that using substantially more arenas than the default is not likely to
377 improve performance, mainly due to reduced cache performance.
378 However, it may make sense to reduce the number of arenas if an application
379 does not make much use of the allocation functions.
380 .Pp
381 In addition to multiple arenas, this allocator supports thread-specific
382 caching for small objects (smaller than one page), in order to make it
383 possible to completely avoid synchronization for most small allocation requests.
384 Such caching allows very fast allocation in the common case, but it increases
385 memory usage and fragmentation, since a bounded number of objects can remain
386 allocated in each thread cache.
387 .Pp
388 Memory is conceptually broken into equal-sized chunks, where the chunk size is
389 a power of two that is greater than the page size.
390 Chunks are always aligned to multiples of the chunk size.
391 This alignment makes it possible to find metadata for user objects very
392 quickly.
393 .Pp
394 User objects are broken into three categories according to size: small, large,
395 and huge.
396 Small objects are smaller than one page.
397 Large objects are smaller than the chunk size.
398 Huge objects are a multiple of the chunk size.
399 Small and large objects are managed by arenas; huge objects are managed
400 separately in a single data structure that is shared by all threads.
401 Huge objects are used by applications infrequently enough that this single
402 data structure is not a scalability issue.
403 .Pp
404 Each chunk that is managed by an arena tracks its contents as runs of
405 contiguous pages (unused, backing a set of small objects, or backing one large
406 object).
407 The combination of chunk alignment and chunk page maps makes it possible to
408 determine all metadata regarding small and large allocations in constant time.
409 .Pp
410 Small objects are managed in groups by page runs.
411 Each run maintains a bitmap that tracks which regions are in use.
412 Allocation requests that are no more than half the quantum (8 or 16, depending
413 on architecture) are rounded up to the nearest power of two.
414 Allocation requests that are more than half the quantum, but no more than the
415 minimum cacheline-multiple size class (see the
416 .Dq Q
417 option) are rounded up to the nearest multiple of the quantum.
418 Allocation requests that are more than the minumum cacheline-multiple size
419 class, but no more than the minimum subpage-multiple size class (see the
420 .Dq C
421 option) are rounded up to the nearest multiple of the cacheline size (64).
422 Allocation requests that are more than the minimum subpage-multiple size class
423 are rounded up to the nearest multiple of the subpage size (256).
424 Allocation requests that are more than one page, but small enough to fit in
425 an arena-managed chunk (see the
426 .Dq K
427 option), are rounded up to the nearest run size.
428 Allocation requests that are too large to fit in an arena-managed chunk are
429 rounded up to the nearest multiple of the chunk size.
430 .Pp
431 Allocations are packed tightly together, which can be an issue for
432 multi-threaded applications.
433 If you need to assure that allocations do not suffer from cacheline sharing,
434 round your allocation requests up to the nearest multiple of the cacheline
435 size.
436 .Sh DEBUGGING MALLOC PROBLEMS
437 The first thing to do is to set the
438 .Dq A
439 option.
440 This option forces a coredump (if possible) at the first sign of trouble,
441 rather than the normal policy of trying to continue if at all possible.
442 .Pp
443 It is probably also a good idea to recompile the program with suitable
444 options and symbols for debugger support.
445 .Pp
446 If the program starts to give unusual results, coredump or generally behave
447 differently without emitting any of the messages mentioned in the next
448 section, it is likely because it depends on the storage being filled with
449 zero bytes.
450 Try running it with the
451 .Dq Z
452 option set;
453 if that improves the situation, this diagnosis has been confirmed.
454 If the program still misbehaves,
455 the likely problem is accessing memory outside the allocated area.
456 .Pp
457 Alternatively, if the symptoms are not easy to reproduce, setting the
458 .Dq J
459 option may help provoke the problem.
460 .Pp
461 In truly difficult cases, the
462 .Dq U
463 option, if supported by the kernel, can provide a detailed trace of
464 all calls made to these functions.
465 .Pp
466 Unfortunately this implementation does not provide much detail about
467 the problems it detects; the performance impact for storing such information
468 would be prohibitive.
469 There are a number of allocator implementations available on the Internet
470 which focus on detecting and pinpointing problems by trading performance for
471 extra sanity checks and detailed diagnostics.
472 .Sh DIAGNOSTIC MESSAGES
473 If any of the memory allocation/deallocation functions detect an error or
474 warning condition, a message will be printed to file descriptor
475 .Dv STDERR_FILENO .
476 Errors will result in the process dumping core.
477 If the
478 .Dq A
479 option is set, all warnings are treated as errors.
480 .Pp
481 The
482 .Va _malloc_message
483 variable allows the programmer to override the function which emits
484 the text strings forming the errors and warnings if for some reason
485 the
486 .Dv stderr
487 file descriptor is not suitable for this.
488 Please note that doing anything which tries to allocate memory in
489 this function is likely to result in a crash or deadlock.
490 .Pp
491 All messages are prefixed by
492 .Dq Ao Ar progname Ac Ns Li : (malloc) .
493 .Sh RETURN VALUES
494 The
495 .Fn malloc
496 and
497 .Fn calloc
498 functions return a pointer to the allocated memory if successful; otherwise
499 a
500 .Dv NULL
501 pointer is returned and
502 .Va errno
503 is set to
504 .Er ENOMEM .
505 .Pp
506 The
507 .Fn realloc
508 and
509 .Fn reallocf
510 functions return a pointer, possibly identical to
511 .Fa ptr ,
512 to the allocated memory
513 if successful; otherwise a
514 .Dv NULL
515 pointer is returned, and
516 .Va errno
517 is set to
518 .Er ENOMEM
519 if the error was the result of an allocation failure.
520 The
521 .Fn realloc
522 function always leaves the original buffer intact
523 when an error occurs, whereas
524 .Fn reallocf
525 deallocates it in this case.
526 .Pp
527 The
528 .Fn free
529 function returns no value.
530 .Pp
531 The
532 .Fn malloc_usable_size
533 function returns the usable size of the allocation pointed to by
534 .Fa ptr .
535 .Sh ENVIRONMENT
536 The following environment variables affect the execution of the allocation
537 functions:
538 .Bl -tag -width ".Ev MALLOC_OPTIONS"
539 .It Ev MALLOC_OPTIONS
540 If the environment variable
541 .Ev MALLOC_OPTIONS
542 is set, the characters it contains will be interpreted as flags to the
543 allocation functions.
544 .El
545 .Sh EXAMPLES
546 To dump core whenever a problem occurs:
547 .Pp
548 .Bd -literal -offset indent
549 ln -s 'A' /etc/malloc.conf
550 .Ed
551 .Pp
552 To specify in the source that a program does no return value checking
553 on calls to these functions:
554 .Bd -literal -offset indent
555 _malloc_options = "X";
556 .Ed
557 .Sh SEE ALSO
558 .Xr limits 1 ,
559 .Xr madvise 2 ,
560 .Xr mmap 2 ,
561 .Xr sbrk 2 ,
562 .Xr alloca 3 ,
563 .Xr atexit 3 ,
564 .Xr getpagesize 3 ,
565 .Xr getpagesizes 3 ,
566 .Xr memory 3 ,
567 .Xr posix_memalign 3
568 .Sh STANDARDS
569 The
570 .Fn malloc ,
571 .Fn calloc ,
572 .Fn realloc
573 and
574 .Fn free
575 functions conform to
576 .St -isoC .
577 .Sh HISTORY
578 The
579 .Fn reallocf
580 function first appeared in
581 .Fx 3.0 .
582 .Pp
583 The
584 .Fn malloc_usable_size
585 function first appeared in
586 .Fx 7.0 .