]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libc/stdlib/malloc.3
This commit was generated by cvs2svn to compensate for changes in r170964,
[FreeBSD/FreeBSD.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 June 15, 2007
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 value of the newly allocated portion of the memory is 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, character by character as flags.
169 .Pp
170 Most flags are single letters,
171 where uppercase indicates that the behavior is set, or on,
172 and lowercase means that the behavior is not set, or off.
173 .Bl -tag -width indent
174 .It A
175 All warnings (except for the warning about unknown
176 flags being set) become fatal.
177 The process will call
178 .Xr abort 3
179 in these cases.
180 .It H
181 Use
182 .Xr madvise 2
183 when pages within a chunk are no longer in use, but the chunk as a whole cannot
184 yet be deallocated.
185 This is primarily of use when swapping is a real possibility, due to the high
186 overhead of the
187 .Fn madvise
188 system call.
189 .It J
190 Each byte of new memory allocated by
191 .Fn malloc ,
192 .Fn realloc
193 or
194 .Fn reallocf
195 will be initialized to 0xa5.
196 All memory returned by
197 .Fn free ,
198 .Fn realloc
199 or
200 .Fn reallocf
201 will be initialized to 0x5a.
202 This is intended for debugging and will impact performance negatively.
203 .It K
204 Increase/decrease the virtual memory chunk size by a factor of two.
205 The default chunk size is 1 MB.
206 This option can be specified multiple times.
207 .It N
208 Increase/decrease the number of arenas by a factor of two.
209 The default number of arenas is four times the number of CPUs, or one if there
210 is a single CPU.
211 This option can be specified multiple times.
212 .It P
213 Various statistics are printed at program exit via an
214 .Xr atexit 3
215 function.
216 This has the potential to cause deadlock for a multi-threaded process that exits
217 while one or more threads are executing in the memory allocation functions.
218 Therefore, this option should only be used with care; it is primarily intended
219 as a performance tuning aid during application development.
220 .It Q
221 Increase/decrease the size of the allocation quantum by a factor of two.
222 The default quantum is the minimum allowed by the architecture (typically 8 or
223 16 bytes).
224 This option can be specified multiple times.
225 .It S
226 Increase/decrease the size of the maximum size class that is a multiple of the
227 quantum by a factor of two.
228 Above this size, power-of-two spacing is used for size classes.
229 The default value is 512 bytes.
230 This option can be specified multiple times.
231 .It U
232 Generate
233 .Dq utrace
234 entries for
235 .Xr ktrace 1 ,
236 for all operations.
237 Consult the source for details on this option.
238 .It V
239 Attempting to allocate zero bytes will return a
240 .Dv NULL
241 pointer instead of
242 a valid pointer.
243 (The default behavior is to make a minimal allocation and return a
244 pointer to it.)
245 This option is provided for System V compatibility.
246 This option is incompatible with the
247 .Dq X
248 option.
249 .It X
250 Rather than return failure for any allocation function,
251 display a diagnostic message on
252 .Dv stderr
253 and cause the program to drop
254 core (using
255 .Xr abort 3 ) .
256 This option should be set at compile time by including the following in
257 the source code:
258 .Bd -literal -offset indent
259 _malloc_options = "X";
260 .Ed
261 .It Z
262 Each byte of new memory allocated by
263 .Fn malloc ,
264 .Fn realloc
265 or
266 .Fn reallocf
267 will be initialized to 0.
268 Note that this initialization only happens once for each byte, so
269 .Fn realloc
270 and
271 .Fn reallocf
272 calls do not zero memory that was previously allocated.
273 This is intended for debugging and will impact performance negatively.
274 .El
275 .Pp
276 The
277 .Dq J
278 and
279 .Dq Z
280 options are intended for testing and debugging.
281 An application which changes its behavior when these options are used
282 is flawed.
283 .Sh IMPLEMENTATION NOTES
284 Traditionally, allocators have used
285 .Xr sbrk 2
286 to obtain memory, but this implementation uses
287 .Xr mmap 2 ,
288 and only uses
289 .Xr sbrk 2
290 under limited circumstances, and only for 32-bit architectures.
291 As a result, the
292 .Ar datasize
293 resource limit has little practical effect for typical applications.
294 The
295 .Ar vmemoryuse
296 resource limit, however, can be used to bound the total virtual memory used by
297 a process, as described in
298 .Xr limits 1 .
299 .Pp
300 This allocator uses multiple arenas in order to reduce lock contention for
301 threaded programs on multi-processor systems.
302 This works well with regard to threading scalability, but incurs some costs.
303 There is a small fixed per-arena overhead, and additionally, arenas manage
304 memory completely independently of each other, which means a small fixed
305 increase in overall memory fragmentation.
306 These overheads are not generally an issue, given the number of arenas normally
307 used.
308 Note that using substantially more arenas than the default is not likely to
309 improve performance, mainly due to reduced cache performance.
310 However, it may make sense to reduce the number of arenas if an application
311 does not make much use of the allocation functions.
312 .Pp
313 Memory is conceptually broken into equal-sized chunks, where the chunk size is
314 a power of two that is greater than the page size.
315 Chunks are always aligned to multiples of the chunk size.
316 This alignment makes it possible to find metadata for user objects very
317 quickly.
318 .Pp
319 User objects are broken into three categories according to size: small, large,
320 and huge.
321 Small objects are no larger than one half of a page.
322 Large objects are smaller than the chunk size.
323 Huge objects are a multiple of the chunk size.
324 Small and large objects are managed by arenas; huge objects are managed
325 separately in a single data structure that is shared by all threads.
326 Huge objects are used by applications infrequently enough that this single
327 data structure is not a scalability issue.
328 .Pp
329 Each chunk that is managed by an arena tracks its contents in a page map as
330 runs of contiguous pages (unused, backing a set of small objects, or backing
331 one large object).
332 The combination of chunk alignment and chunk page maps makes it possible to
333 determine all metadata regarding small and large allocations in constant time.
334 .Pp
335 Small objects are managed in groups by page runs.
336 Each run maintains a bitmap that tracks which regions are in use.
337 Allocation requests that are no more than half the quantum (see the
338 .Dq Q
339 option) are rounded up to the nearest power of two (typically 2, 4, or 8).
340 Allocation requests that are more than half the quantum, but no more than the
341 maximum quantum-multiple size class (see the
342 .Dq S
343 option) are rounded up to the nearest multiple of the quantum.
344 Allocation requests that are larger than the maximum quantum-multiple size
345 class, but no larger than one half of a page, are rounded up to the nearest
346 power of two.
347 Allocation requests that are larger than half of a page, but small enough to
348 fit in an arena-managed chunk (see the
349 .Dq K
350 option), are rounded up to the nearest run size.
351 Allocation requests that are too large to fit in an arena-managed chunk are
352 rounded up to the nearest multiple of the chunk size.
353 .Pp
354 Allocations are packed tightly together, which can be an issue for
355 multi-threaded applications.
356 If you need to assure that allocations do not suffer from cache line sharing,
357 round your allocation requests up to the nearest multiple of the cache line
358 size.
359 .Sh DEBUGGING MALLOC PROBLEMS
360 The first 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 mentioned in the next
371 section, it is likely because it depends on the storage being filled with
372 zero bytes.
373 Try running it with the
374 .Dq Z
375 option set;
376 if that improves the situation, this diagnosis has been confirmed.
377 If the program still misbehaves,
378 the likely problem is accessing memory outside 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 allocator implementations available on the Internet
393 which focus on detecting and pinpointing problems by trading performance for
394 extra sanity checks and detailed diagnostics.
395 .Sh DIAGNOSTIC MESSAGES
396 If any of the memory allocation/deallocation functions detect an error or
397 warning condition, a message will be printed to file descriptor
398 .Dv STDERR_FILENO .
399 Errors will result in the process dumping core.
400 If the
401 .Dq A
402 option is set, all warnings are treated as errors.
403 .Pp
404 The
405 .Va _malloc_message
406 variable allows the programmer to override the function which emits
407 the text strings forming the errors and warnings if for some reason
408 the
409 .Dv stderr
410 file descriptor is not suitable for this.
411 Please note that doing anything which tries to allocate memory in
412 this function is likely to result in a crash or deadlock.
413 .Pp
414 All messages are prefixed by
415 .Dq Ao Ar progname Ac Ns Li : (malloc) .
416 .Sh RETURN VALUES
417 The
418 .Fn malloc
419 and
420 .Fn calloc
421 functions return a pointer to the allocated memory if successful; otherwise
422 a
423 .Dv NULL
424 pointer is returned and
425 .Va errno
426 is set to
427 .Er ENOMEM .
428 .Pp
429 The
430 .Fn realloc
431 and
432 .Fn reallocf
433 functions return a pointer, possibly identical to
434 .Fa ptr ,
435 to the allocated memory
436 if successful; otherwise a
437 .Dv NULL
438 pointer is returned, and
439 .Va errno
440 is set to
441 .Er ENOMEM
442 if the error was the result of an allocation failure.
443 The
444 .Fn realloc
445 function always leaves the original buffer intact
446 when an error occurs, whereas
447 .Fn reallocf
448 deallocates it in this case.
449 .Pp
450 The
451 .Fn free
452 function returns no value.
453 .Pp
454 The
455 .Fn malloc_usable_size
456 function returns the usable size of the allocation pointed to by
457 .Fa ptr .
458 .Sh ENVIRONMENT
459 The following environment variables affect the execution of the allocation
460 functions:
461 .Bl -tag -width ".Ev MALLOC_OPTIONS"
462 .It Ev MALLOC_OPTIONS
463 If the environment variable
464 .Ev MALLOC_OPTIONS
465 is set, the characters it contains will be interpreted as flags to the
466 allocation functions.
467 .El
468 .Sh EXAMPLES
469 To dump core whenever a problem occurs:
470 .Pp
471 .Bd -literal -offset indent
472 ln -s 'A' /etc/malloc.conf
473 .Ed
474 .Pp
475 To specify in the source that a program does no return value checking
476 on calls to these functions:
477 .Bd -literal -offset indent
478 _malloc_options = "X";
479 .Ed
480 .Sh SEE ALSO
481 .Xr limits 1 ,
482 .Xr madvise 2 ,
483 .Xr mmap 2 ,
484 .Xr sbrk 2 ,
485 .Xr alloca 3 ,
486 .Xr atexit 3 ,
487 .Xr getpagesize 3 ,
488 .Xr memory 3 ,
489 .Xr posix_memalign 3
490 .Sh STANDARDS
491 The
492 .Fn malloc ,
493 .Fn calloc ,
494 .Fn realloc
495 and
496 .Fn free
497 functions conform to
498 .St -isoC .
499 .Sh HISTORY
500 The
501 .Fn reallocf
502 function first appeared in
503 .Fx 3.0 .
504 .Pp
505 The
506 .Fn malloc_usable_size
507 function first appeared in
508 .Fx 7.0 .