]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libc/stdlib/malloc.3
Add an unreachable return statement, in order to avoid a compiler warning
[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 April 4, 2006
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 .Fn malloc_usable_size
147 is not a mechanism for in-place
148 .Fn realloc ;
149 rather it is provided soley as a tool for introspection purposes.
150 Any discrepancy between the requested allocation size and the size reported by
151 .Fn malloc_usable_size
152 should not be depended on, since such behavior is entirely
153 implementation-dependent.
154 .Sh TUNING
155 Once, when the first call is made to one of these memory allocation
156 routines, various flags will be set or reset, which affect the
157 workings of this allocator implementation.
158 .Pp
159 The
160 .Dq name
161 of the file referenced by the symbolic link named
162 .Pa /etc/malloc.conf ,
163 the value of the environment variable
164 .Ev MALLOC_OPTIONS ,
165 and the string pointed to by the global variable
166 .Va _malloc_options
167 will be interpreted, in that order, character by character as flags.
168 .Pp
169 Most flags are single letters,
170 where uppercase indicates that the behavior is set, or on,
171 and lowercase means that the behavior is not set, or off.
172 .Bl -tag -width indent
173 .It A
174 All warnings (except for the warning about unknown
175 flags being set) become fatal.
176 The process will call
177 .Xr abort 3
178 in these cases.
179 .It H
180 Use 
181 .Xr madvise 2
182 when pages within a chunk are no longer in use, but the chunk as a whole cannot
183 yet be deallocated.
184 This is primarily of use when swapping is a real possibility, due to the high
185 overhead of the
186 .Fn madvise
187 system call.
188 .It J
189 Each byte of new memory allocated by
190 .Fn malloc ,
191 .Fn realloc
192 or
193 .Fn reallocf
194 will be initialized to 0xa5.
195 All memory returned by
196 .Fn free ,
197 .Fn realloc
198 or
199 .Fn reallocf
200 will be initialized to 0x5a.
201 This is intended for debugging and will impact performance negatively.
202 .It K
203 Increase/decrease the virtual memory chunk size by a factor of two.
204 The default chunk size is 2 MB.
205 This option can be specified multiple times.
206 .It N
207 Increase/decrease the number of arenas by a factor of two.
208 The default number of arenas is four times the number of CPUs, or one if there
209 is a single CPU.
210 This option can be specified multiple times.
211 .It P
212 Various statistics are printed at program exit via an
213 .Xr atexit 3
214 function.
215 This has the potential to cause deadlock for a multi-threaded process that exits
216 while one or more threads are executing in the memory allocation functions.
217 Therefore, this option should only be used with care; it is primarily intended
218 as a performance tuning aid during application development.
219 .It Q
220 Increase/decrease the size of the allocation quantum by a factor of two.
221 The default quantum is the minimum allowed by the architecture (typically 8 or
222 16 bytes).
223 This option can be specified multiple times.
224 .It S
225 Increase/decrease the size of the maximum size class that is a multiple of the
226 quantum by a factor of two.
227 Above this size, power-of-two spacing is used for size classes.
228 The default value is 512 bytes.
229 This option can be specified multiple times.
230 .It U
231 Generate
232 .Dq utrace
233 entries for
234 .Xr ktrace 1 ,
235 for all operations.
236 Consult the source for details on this option.
237 .It V
238 Attempting to allocate zero bytes will return a
239 .Dv NULL
240 pointer instead of
241 a valid pointer.
242 (The default behavior is to make a minimal allocation and return a
243 pointer to it.)
244 This option is provided for System V compatibility.
245 This option is incompatible with the
246 .Dq X
247 option.
248 .It X
249 Rather than return failure for any allocation function,
250 display a diagnostic message on
251 .Dv stderr
252 and cause the program to drop
253 core (using
254 .Xr abort 3 ) .
255 This option should be set at compile time by including the following in
256 the source code:
257 .Bd -literal -offset indent
258 _malloc_options = "X";
259 .Ed
260 .It Z
261 Each byte of new memory allocated by
262 .Fn malloc ,
263 .Fn realloc
264 or
265 .Fn reallocf
266 will be initialized to 0x0.
267 Note that this initialization only happens once for each byte, so
268 .Fn realloc
269 and
270 .Fn reallocf
271 calls do not zero memory that was previously allocated.
272 This is intended for debugging and will impact performance negatively.
273 .El
274 .Pp
275 The
276 .Dq J
277 and
278 .Dq Z
279 options are intended for testing and debugging.
280 An application which changes its behavior when these options are used
281 is flawed.
282 .Sh RETURN VALUES
283 The
284 .Fn malloc
285 and
286 .Fn calloc
287 functions return a pointer to the allocated memory if successful; otherwise
288 a
289 .Dv NULL
290 pointer is returned and
291 .Va errno
292 is set to
293 .Er ENOMEM .
294 .Pp
295 The
296 .Fn realloc
297 and
298 .Fn reallocf
299 functions return a pointer, possibly identical to
300 .Fa ptr ,
301 to the allocated memory
302 if successful; otherwise a
303 .Dv NULL
304 pointer is returned, and
305 .Va errno
306 is set to
307 .Er ENOMEM
308 if the error was the result of an allocation failure.
309 The
310 .Fn realloc
311 function always leaves the original buffer intact
312 when an error occurs, whereas
313 .Fn reallocf
314 deallocates it in this case.
315 .Pp
316 The
317 .Fn free
318 function returns no value.
319 .Pp
320 The
321 .Fn malloc_usable_size
322 function returns the usable size of the allocation pointed to by
323 .Fa ptr .
324 .Sh IMPLEMENTATION NOTES
325 This allocator uses multiple arenas in order to reduce lock contention for
326 threaded programs on multi-processor systems.
327 This works well with regard to threading scalability, but incurs some costs.
328 There is a small fixed per-arena overhead, and additionally, arenas manage
329 memory completely independently of each other, which means a small fixed
330 increase in overall memory fragmentation.
331 These overheads are not generally an issue, given the number of arenas normally
332 used.
333 Note that using substantially more arenas than the default is not likely to
334 improve performance, mainly due to reduced cache performance.
335 However, it may make sense to reduce the number of arenas if an application
336 does not make much use of the allocation functions.
337 .Pp
338 Chunks manage their pages by using a power-of-two buddy allocation strategy.
339 Each chunk maintains a page map that makes it possible to determine the state
340 of any page in the chunk in constant time.
341 Allocations that are no larger than one half of a page are managed in groups by
342 page
343 .Dq runs .
344 Each run maintains a bitmap that tracks which regions are in use.
345 Allocation requests that are no more than half the quantum (see the
346 .Dq Q
347 option) are rounded up to the nearest power of two (typically 2, 4, or 8).
348 Allocation requests that are more than half the quantum, but no more than the
349 maximum quantum-multiple size class (see the
350 .Dq S
351 option) are rounded up to the nearest multiple of the quantum.
352 Allocation requests that are larger than the maximum quantum-multiple size
353 class, but no larger than one half of a page, are rounded up to the nearest
354 power of two.
355 Allocation requests that are larger than half of a page, but no larger than half
356 of a chunk (see the 
357 .Dq K
358 option), are rounded up to the nearest run size.
359 Allocation requests that are larger than half of a chunk are rounded up to the
360 nearest multiple of the chunk size.
361 .Pp
362 Allocations are packed tightly together, which can be an issue for
363 multi-threaded applications.
364 If you need to assure that allocations do not suffer from cache line sharing,
365 round your allocation requests up to the nearest multiple of the cache line
366 size.
367 .Sh DEBUGGING MALLOC PROBLEMS
368 The first thing to do is to set the
369 .Dq A
370 option.
371 This option forces a coredump (if possible) at the first sign of trouble,
372 rather than the normal policy of trying to continue if at all possible.
373 .Pp
374 It is probably also a good idea to recompile the program with suitable
375 options and symbols for debugger support.
376 .Pp
377 If the program starts to give unusual results, coredump or generally behave
378 differently without emitting any of the messages mentioned in the next
379 section, it is likely because it depends on the storage being filled with
380 zero bytes.
381 Try running it with the
382 .Dq Z
383 option set;
384 if that improves the situation, this diagnosis has been confirmed.
385 If the program still misbehaves,
386 the likely problem is accessing memory outside the allocated area.
387 .Pp
388 Alternatively, if the symptoms are not easy to reproduce, setting the
389 .Dq J
390 option may help provoke the problem.
391 .Pp
392 In truly difficult cases, the
393 .Dq U
394 option, if supported by the kernel, can provide a detailed trace of
395 all calls made to these functions.
396 .Pp
397 Unfortunately this implementation does not provide much detail about
398 the problems it detects; the performance impact for storing such information
399 would be prohibitive.
400 There are a number of allocation implementations available on the Internet
401 which focus on detecting and pinpointing problems by trading performance for
402 extra sanity checks and detailed diagnostics.
403 .Sh DIAGNOSTIC MESSAGES
404 If any of the memory allocation/deallocation functions detect an error or
405 warning condition, a message will be printed to file descriptor STDERR_FILENO.
406 Errors will result in the process dumping core.
407 If the
408 .Dq A
409 option is set, all warnings are treated as errors.
410 .Pp
411 The
412 .Va _malloc_message
413 variable allows the programmer to override the function which emits
414 the text strings forming the errors and warnings if for some reason
415 the
416 .Dv stderr
417 file descriptor is not suitable for this.
418 Please note that doing anything which tries to allocate memory in
419 this function is likely to result in a crash or deadlock.
420 .Pp
421 All messages are prefixed by:
422 .Bl -diag
423 .It <progname>: (malloc)
424 .El
425 .Sh ENVIRONMENT
426 The following environment variables affect the execution of the allocation
427 functions:
428 .Bl -tag -width ".Ev MALLOC_OPTIONS"
429 .It Ev MALLOC_OPTIONS
430 If the environment variable
431 .Ev MALLOC_OPTIONS
432 is set, the characters it contains will be interpreted as flags to the
433 allocation functions.
434 .El
435 .Sh EXAMPLES
436 To dump core whenever a problem occurs:
437 .Pp
438 .Bd -literal -offset indent
439 ln -s 'A' /etc/malloc.conf
440 .Ed
441 .Pp
442 To specify in the source that a program does no return value checking
443 on calls to these functions:
444 .Bd -literal -offset indent
445 _malloc_options = "X";
446 .Ed
447 .Sh SEE ALSO
448 .Xr madvise 2 ,
449 .Xr mmap 2 ,
450 .Xr alloca 3 ,
451 .Xr atexit 3 ,
452 .Xr getpagesize 3 ,
453 .Xr memory 3 ,
454 .Xr posix_memalign 3
455 .Sh STANDARDS
456 The
457 .Fn malloc ,
458 .Fn calloc ,
459 .Fn realloc
460 and
461 .Fn free
462 functions conform to
463 .St -isoC .
464 .Sh HISTORY
465 The
466 .Fn reallocf
467 function first appeared in
468 .Fx 3.0 .
469 .Pp
470 The
471 .Fn malloc_usable_size
472 function first appeared in
473 .Fx 7.0 .