1.\" $NetBSD: malloc.3,v 1.33 2010/04/30 07:16:35 jruoho Exp $ 2.\" 3.\" Copyright (c) 1980, 1991, 1993 4.\" The Regents of the University of California. All rights reserved. 5.\" 6.\" This code is derived from software contributed to Berkeley by 7.\" the American National Standards Committee X3, on Information 8.\" Processing Systems. 9.\" 10.\" Redistribution and use in source and binary forms, with or without 11.\" modification, are permitted provided that the following conditions 12.\" are met: 13.\" 1. Redistributions of source code must retain the above copyright 14.\" notice, this list of conditions and the following disclaimer. 15.\" 2. Redistributions in binary form must reproduce the above copyright 16.\" notice, this list of conditions and the following disclaimer in the 17.\" documentation and/or other materials provided with the distribution. 18.\" 3. Neither the name of the University nor the names of its contributors 19.\" may be used to endorse or promote products derived from this software 20.\" without specific prior written permission. 21.\" 22.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 23.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 24.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 25.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 26.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 27.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 28.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 29.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 30.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 31.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 32.\" SUCH DAMAGE. 33.\" 34.\" @(#)malloc.3 8.1 (Berkeley) 6/4/93 35.\" $FreeBSD: src/lib/libc/stdlib/malloc.3,v 1.73 2007/06/15 22:32:33 jasone Exp $ 36.\" 37.Dd April 30, 2010 38.Dt MALLOC 3 39.Os 40.Sh NAME 41.Nm malloc , calloc , realloc , free 42.Nd general purpose memory allocation functions 43.Sh LIBRARY 44.Lb libc 45.Sh SYNOPSIS 46.In stdlib.h 47.Ft void * 48.Fn malloc "size_t size" 49.Ft void * 50.Fn calloc "size_t number" "size_t size" 51.Ft void * 52.Fn realloc "void *ptr" "size_t size" 53.Ft void 54.Fn free "void *ptr" 55.Ft const char * 56.Va _malloc_options ; 57.Sh DESCRIPTION 58The 59.Fn malloc 60function allocates 61.Fa size 62bytes of uninitialized memory. 63The allocated space is suitably aligned (after possible pointer coercion) 64for storage of any type of object. 65.Pp 66The 67.Fn calloc 68function allocates space for 69.Fa number 70objects, 71each 72.Fa size 73bytes in length. 74The result is identical to calling 75.Fn malloc 76with an argument of 77.Dq "number * size" , 78with the exception that the allocated memory is explicitly initialized 79to zero bytes. 80.Pp 81When using 82.Fn malloc 83be careful to avoid the following idiom: 84.Bd -literal -offset indent 85if ((p = malloc(number * size)) == NULL) 86 err(EXIT_FAILURE, "malloc"); 87.Ed 88.Pp 89The multiplication may lead to an integer overflow. 90To avoid this, 91.Fn calloc 92is recommended. 93.Pp 94If 95.Fn malloc 96must be used, be sure to test for overflow: 97.Bd -literal -offset indent 98if (size && number > SIZE_MAX / size) { 99 errno = EOVERFLOW; 100 err(EXIT_FAILURE, "overflow"); 101} 102.Ed 103.Pp 104The 105.Fn realloc 106function changes the size of the previously allocated memory referenced by 107.Fa ptr 108to 109.Fa size 110bytes. 111The contents of the memory are unchanged up to the lesser of the new and 112old sizes. 113If the new size is larger, 114the value of the newly allocated portion of the memory is undefined. 115Upon success, the memory referenced by 116.Fa ptr 117is freed and a pointer to the newly allocated memory is returned. 118Note that 119.Fn realloc 120may move the memory allocation, resulting in a different return value than 121.Fa ptr . 122If 123.Fa ptr 124is 125.Dv NULL , 126the 127.Fn realloc 128function behaves identically to 129.Fn malloc 130for the specified size. 131.Pp 132When using 133.Fn realloc 134one must be careful to avoid the following idiom: 135.Pp 136.Bd -literal -offset indent 137nsize += 50; 138if ((p = realloc(p, nsize)) == NULL) 139 return (NULL); 140.Ed 141.Pp 142Do not adjust the variable describing how much memory has been allocated 143until one knows the allocation has been successful. 144This can cause aberrant program behavior if the incorrect size value is used. 145In most cases, the above sample will also result in a leak of memory. 146As stated earlier, a return value of 147.Dv NULL 148indicates that the old object still remains allocated. 149Better code looks like this: 150.Bd -literal -offset indent 151newsize = size + 50; 152if ((p2 = realloc(p, newsize)) == NULL) { 153 if (p) 154 free(p); 155 p = NULL; 156 return (NULL); 157} 158p = p2; 159size = newsize; 160.Ed 161.Pp 162The 163.Fn free 164function causes the allocated memory referenced by 165.Fa ptr 166to be made available for future allocations. 167If 168.Fa ptr 169is 170.Dv NULL , 171no action occurs. 172.Sh TUNING 173Once, when the first call is made to one of these memory allocation 174routines, various flags will be set or reset, which affect the 175workings of this allocator implementation. 176.Pp 177The 178.Dq name 179of the file referenced by the symbolic link named 180.Pa /etc/malloc.conf , 181the value of the environment variable 182.Ev MALLOC_OPTIONS , 183and the string pointed to by the global variable 184.Va _malloc_options 185will be interpreted, in that order, character by character as flags. 186.Pp 187Most flags are single letters, 188where uppercase indicates that the behavior is set, or on, 189and lowercase means that the behavior is not set, or off. 190.Bl -tag -width indent 191.It A 192All warnings (except for the warning about unknown 193flags being set) become fatal. 194The process will call 195.Xr abort 3 196in these cases. 197.It H 198Use 199.Xr madvise 2 200when pages within a chunk are no longer in use, but the chunk as a whole cannot 201yet be deallocated. 202This is primarily of use when swapping is a real possibility, due to the high 203overhead of the 204.Fn madvise 205system call. 206.It J 207Each byte of new memory allocated by 208.Fn malloc , 209.Fn realloc 210will be initialized to 0xa5. 211All memory returned by 212.Fn free , 213.Fn realloc 214will be initialized to 0x5a. 215This is intended for debugging and will impact performance negatively. 216.It K 217Increase/decrease the virtual memory chunk size by a factor of two. 218The default chunk size is 1 MB. 219This option can be specified multiple times. 220.It N 221Increase/decrease the number of arenas by a factor of two. 222The default number of arenas is four times the number of CPUs, or one if there 223is a single CPU. 224This option can be specified multiple times. 225.It P 226Various statistics are printed at program exit via an 227.Xr atexit 3 228function. 229This has the potential to cause deadlock for a multi-threaded process that exits 230while one or more threads are executing in the memory allocation functions. 231Therefore, this option should only be used with care; it is primarily intended 232as a performance tuning aid during application development. 233.It Q 234Increase/decrease the size of the allocation quantum by a factor of two. 235The default quantum is the minimum allowed by the architecture (typically 8 or 23616 bytes). 237This option can be specified multiple times. 238.It S 239Increase/decrease the size of the maximum size class that is a multiple of the 240quantum by a factor of two. 241Above this size, power-of-two spacing is used for size classes. 242The default value is 512 bytes. 243This option can be specified multiple times. 244.It U 245Generate 246.Dq utrace 247entries for 248.Xr ktrace 1 , 249for all operations. 250Consult the source for details on this option. 251.It V 252Attempting to allocate zero bytes will return a 253.Dv NULL 254pointer instead of a valid pointer. 255(The default behavior is to make a minimal allocation and return a 256pointer to it.) 257This option is provided for System V compatibility. 258This option is incompatible with the 259.Dq X 260option. 261.It X 262Rather than return failure for any allocation function, 263display a diagnostic message on 264.Dv stderr 265and cause the program to drop 266core (using 267.Xr abort 3 ) . 268This option should be set at compile time by including the following in 269the source code: 270.Bd -literal -offset indent 271_malloc_options = "X"; 272.Ed 273.It Z 274Each byte of new memory allocated by 275.Fn malloc , 276.Fn realloc 277will be initialized to 0. 278Note that this initialization only happens once for each byte, so 279.Fn realloc 280does not zero memory that was previously allocated. 281This is intended for debugging and will impact performance negatively. 282.El 283.Pp 284The 285.Dq J 286and 287.Dq Z 288options are intended for testing and debugging. 289An application which changes its behavior when these options are used 290is flawed. 291.Sh IMPLEMENTATION NOTES 292This allocator uses multiple arenas in order to reduce lock contention for 293threaded programs on multi-processor systems. 294This works well with regard to threading scalability, but incurs some costs. 295There is a small fixed per-arena overhead, and additionally, arenas manage 296memory completely independently of each other, which means a small fixed 297increase in overall memory fragmentation. 298These overheads are not generally an issue, given the number of arenas normally 299used. 300Note that using substantially more arenas than the default is not likely to 301improve performance, mainly due to reduced cache performance. 302However, it may make sense to reduce the number of arenas if an application 303does not make much use of the allocation functions. 304.Pp 305Memory is conceptually broken into equal-sized chunks, where the chunk size is 306a power of two that is greater than the page size. 307Chunks are always aligned to multiples of the chunk size. 308This alignment makes it possible to find metadata for user objects very 309quickly. 310.Pp 311User objects are broken into three categories according to size: small, large, 312and huge. 313Small objects are no larger than one half of a page. 314Large objects are smaller than the chunk size. 315Huge objects are a multiple of the chunk size. 316Small and large objects are managed by arenas; huge objects are managed 317separately in a single data structure that is shared by all threads. 318Huge objects are used by applications infrequently enough that this single 319data structure is not a scalability issue. 320.Pp 321Each chunk that is managed by an arena tracks its contents in a page map as 322runs of contiguous pages (unused, backing a set of small objects, or backing 323one large object). 324The combination of chunk alignment and chunk page maps makes it possible to 325determine all metadata regarding small and large allocations in constant time. 326.Pp 327Small objects are managed in groups by page runs. 328Each run maintains a bitmap that tracks which regions are in use. 329Allocation requests that are no more than half the quantum (see the 330.Dq Q 331option) are rounded up to the nearest power of two (typically 2, 4, or 8). 332Allocation requests that are more than half the quantum, but no more than the 333maximum quantum-multiple size class (see the 334.Dq S 335option) are rounded up to the nearest multiple of the quantum. 336Allocation requests that are larger than the maximum quantum-multiple size 337class, but no larger than one half of a page, are rounded up to the nearest 338power of two. 339Allocation requests that are larger than half of a page, but small enough to 340fit in an arena-managed chunk (see the 341.Dq K 342option), are rounded up to the nearest run size. 343Allocation requests that are too large to fit in an arena-managed chunk are 344rounded up to the nearest multiple of the chunk size. 345.Pp 346Allocations are packed tightly together, which can be an issue for 347multi-threaded applications. 348If you need to assure that allocations do not suffer from cache line sharing, 349round your allocation requests up to the nearest multiple of the cache line 350size. 351.Sh DEBUGGING MALLOC PROBLEMS 352The first thing to do is to set the 353.Dq A 354option. 355This option forces a coredump (if possible) at the first sign of trouble, 356rather than the normal policy of trying to continue if at all possible. 357.Pp 358It is probably also a good idea to recompile the program with suitable 359options and symbols for debugger support. 360.Pp 361If the program starts to give unusual results, coredump or generally behave 362differently without emitting any of the messages mentioned in the next 363section, it is likely because it depends on the storage being filled with 364zero bytes. 365Try running it with the 366.Dq Z 367option set; 368if that improves the situation, this diagnosis has been confirmed. 369If the program still misbehaves, 370the likely problem is accessing memory outside the allocated area. 371.Pp 372Alternatively, if the symptoms are not easy to reproduce, setting the 373.Dq J 374option may help provoke the problem. 375.Pp 376In truly difficult cases, the 377.Dq U 378option, if supported by the kernel, can provide a detailed trace of 379all calls made to these functions. 380.Pp 381Unfortunately this implementation does not provide much detail about 382the problems it detects; the performance impact for storing such information 383would be prohibitive. 384There are a number of allocator implementations available on the Internet 385which focus on detecting and pinpointing problems by trading performance for 386extra sanity checks and detailed diagnostics. 387.Sh DIAGNOSTIC MESSAGES 388If any of the memory allocation/deallocation functions detect an error or 389warning condition, a message will be printed to file descriptor 390.Dv STDERR_FILENO . 391Errors will result in the process dumping core. 392If the 393.Dq A 394option is set, all warnings are treated as errors. 395.Pp 396The 397.Va _malloc_message 398variable allows the programmer to override the function which emits 399the text strings forming the errors and warnings if for some reason 400the 401.Dv stderr 402file descriptor is not suitable for this. 403Please note that doing anything which tries to allocate memory in 404this function is likely to result in a crash or deadlock. 405.Pp 406All messages are prefixed by 407.Dq Ao Ar progname Ac Ns Li \&: Pq malloc . 408.Sh RETURN VALUES 409The 410.Fn malloc 411and 412.Fn calloc 413functions return a pointer to the allocated memory if successful; otherwise 414a 415.Dv NULL 416pointer is returned and 417.Va errno 418is set to 419.Er ENOMEM . 420.Pp 421The 422.Fn realloc 423function returns a pointer, possibly identical to 424.Fa ptr , 425to the allocated memory 426if successful; otherwise a 427.Dv NULL 428pointer is returned, and 429.Va errno 430is set to 431.Er ENOMEM 432if the error was the result of an allocation failure. 433The 434.Fn realloc 435function always leaves the original buffer intact 436when an error occurs. 437.Pp 438The 439.Fn free 440function returns no value. 441.Sh ENVIRONMENT 442The following environment variables affect the execution of the allocation 443functions: 444.Bl -tag -width ".Ev MALLOC_OPTIONS" 445.It Ev MALLOC_OPTIONS 446If the environment variable 447.Ev MALLOC_OPTIONS 448is set, the characters it contains will be interpreted as flags to the 449allocation functions. 450.El 451.Sh EXAMPLES 452To dump core whenever a problem occurs: 453.Pp 454.Bd -literal -offset indent 455ln -s 'A' /etc/malloc.conf 456.Ed 457.Pp 458To specify in the source that a program does no return value checking 459on calls to these functions: 460.Bd -literal -offset indent 461_malloc_options = "X"; 462.Ed 463.Sh SEE ALSO 464.\" .Xr limits 1 , 465.Xr madvise 2 , 466.Xr mmap 2 , 467.Xr sbrk 2 , 468.Xr alloca 3 , 469.Xr atexit 3 , 470.Xr getpagesize 3 , 471.Xr memory 3 , 472.Xr posix_memalign 3 473.Sh STANDARDS 474The 475.Fn malloc , 476.Fn calloc , 477.Fn realloc 478and 479.Fn free 480functions conform to 481.St -isoC . 482