1.\" $NetBSD: malloc.3,v 1.34 2010/05/03 03:47:51 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 May 3, 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 Em 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 Em 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 Em 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 Em 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 Em 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 Em 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 Em 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 Em 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 Em U 245Generate 246.Dq utrace 247entries for 248.Xr ktrace 1 , 249for all operations. 250Consult the source for details on this option. 251.It Em 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.Em X 260option. 261.It Em 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.Pp 274.It Em Z 275Each byte of new memory allocated by 276.Fn malloc , 277.Fn realloc 278will be initialized to 0. 279Note that this initialization only happens once for each byte, so 280.Fn realloc 281does not zero memory that was previously allocated. 282This is intended for debugging and will impact performance negatively. 283.El 284.Pp 285The 286.Em J 287and 288.Em Z 289options are intended for testing and debugging. 290An application which changes its behavior when these options are used 291is flawed. 292.Sh IMPLEMENTATION NOTES 293This allocator uses multiple arenas in order to reduce lock contention for 294threaded programs on multi-processor systems. 295This works well with regard to threading scalability, but incurs some costs. 296There is a small fixed per-arena overhead, and additionally, arenas manage 297memory completely independently of each other, which means a small fixed 298increase in overall memory fragmentation. 299These overheads are not generally an issue, given the number of arenas normally 300used. 301Note that using substantially more arenas than the default is not likely to 302improve performance, mainly due to reduced cache performance. 303However, it may make sense to reduce the number of arenas if an application 304does not make much use of the allocation functions. 305.Pp 306Memory is conceptually broken into equal-sized chunks, where the chunk size is 307a power of two that is greater than the page size. 308Chunks are always aligned to multiples of the chunk size. 309This alignment makes it possible to find metadata for user objects very 310quickly. 311.Pp 312User objects are broken into three categories according to size: small, large, 313and huge. 314Small objects are no larger than one half of a page. 315Large objects are smaller than the chunk size. 316Huge objects are a multiple of the chunk size. 317Small and large objects are managed by arenas; huge objects are managed 318separately in a single data structure that is shared by all threads. 319Huge objects are used by applications infrequently enough that this single 320data structure is not a scalability issue. 321.Pp 322Each chunk that is managed by an arena tracks its contents in a page map as 323runs of contiguous pages (unused, backing a set of small objects, or backing 324one large object). 325The combination of chunk alignment and chunk page maps makes it possible to 326determine all metadata regarding small and large allocations in constant time. 327.Pp 328Small objects are managed in groups by page runs. 329Each run maintains a bitmap that tracks which regions are in use. 330Allocation requests that are no more than half the quantum (see the 331.Em Q 332option) are rounded up to the nearest power of two (typically 2, 4, or 8). 333Allocation requests that are more than half the quantum, but no more than the 334maximum quantum-multiple size class (see the 335.Em S 336option) are rounded up to the nearest multiple of the quantum. 337Allocation requests that are larger than the maximum quantum-multiple size 338class, but no larger than one half of a page, are rounded up to the nearest 339power of two. 340Allocation requests that are larger than half of a page, but small enough to 341fit in an arena-managed chunk (see the 342.Em K 343option), are rounded up to the nearest run size. 344Allocation requests that are too large to fit in an arena-managed chunk are 345rounded up to the nearest multiple of the chunk size. 346.Pp 347Allocations are packed tightly together, which can be an issue for 348multi-threaded applications. 349If you need to assure that allocations do not suffer from cache line sharing, 350round your allocation requests up to the nearest multiple of the cache line 351size. 352.Sh DEBUGGING MALLOC PROBLEMS 353The first thing to do is to set the 354.Em A 355option. 356This option forces a coredump (if possible) at the first sign of trouble, 357rather than the normal policy of trying to continue if at all possible. 358.Pp 359It is probably also a good idea to recompile the program with suitable 360options and symbols for debugger support. 361.Pp 362If the program starts to give unusual results, coredump or generally behave 363differently without emitting any of the messages mentioned in the next 364section, it is likely because it depends on the storage being filled with 365zero bytes. 366Try running it with the 367.Em Z 368option set; 369if that improves the situation, this diagnosis has been confirmed. 370If the program still misbehaves, 371the likely problem is accessing memory outside the allocated area. 372.Pp 373Alternatively, if the symptoms are not easy to reproduce, setting the 374.Em J 375option may help provoke the problem. 376.Pp 377In truly difficult cases, the 378.Em U 379option, if supported by the kernel, can provide a detailed trace of 380all calls made to these functions. 381.Pp 382Unfortunately this implementation does not provide much detail about 383the problems it detects; the performance impact for storing such information 384would be prohibitive. 385There are a number of allocator implementations available on the Internet 386which focus on detecting and pinpointing problems by trading performance for 387extra sanity checks and detailed diagnostics. 388.Sh DIAGNOSTIC MESSAGES 389If any of the memory allocation/deallocation functions detect an error or 390warning condition, a message will be printed to file descriptor 391.Dv STDERR_FILENO . 392Errors will result in the process dumping core. 393If the 394.Em A 395option is set, all warnings are treated as errors. 396.Pp 397The 398.Va _malloc_message 399variable allows the programmer to override the function which emits 400the text strings forming the errors and warnings if for some reason 401the 402.Dv stderr 403file descriptor is not suitable for this. 404Please note that doing anything which tries to allocate memory in 405this function is likely to result in a crash or deadlock. 406.Pp 407All messages are prefixed by 408.Dq Ao Ar progname Ac Ns Li \&: Pq malloc . 409.Sh RETURN VALUES 410The 411.Fn malloc 412and 413.Fn calloc 414functions return a pointer to the allocated memory if successful; otherwise 415a 416.Dv NULL 417pointer is returned and 418.Va errno 419is set to 420.Er ENOMEM . 421.Pp 422The 423.Fn realloc 424function returns a pointer, possibly identical to 425.Fa ptr , 426to the allocated memory 427if successful; otherwise a 428.Dv NULL 429pointer is returned, and 430.Va errno 431is set to 432.Er ENOMEM 433if the error was the result of an allocation failure. 434The 435.Fn realloc 436function always leaves the original buffer intact 437when an error occurs. 438.Pp 439The 440.Fn free 441function returns no value. 442.Sh ENVIRONMENT 443The following environment variables affect the execution of the allocation 444functions: 445.Bl -tag -width ".Ev MALLOC_OPTIONS" 446.It Ev MALLOC_OPTIONS 447If the environment variable 448.Ev MALLOC_OPTIONS 449is set, the characters it contains will be interpreted as flags to the 450allocation functions. 451.El 452.Sh EXAMPLES 453To dump core whenever a problem occurs: 454.Pp 455.Bd -literal -offset indent 456ln -s 'A' /etc/malloc.conf 457.Ed 458.Pp 459To specify in the source that a program does no return value checking 460on calls to these functions: 461.Bd -literal -offset indent 462_malloc_options = "X"; 463.Ed 464.Sh SEE ALSO 465.\" .Xr limits 1 , 466.Xr madvise 2 , 467.Xr mmap 2 , 468.Xr sbrk 2 , 469.Xr alloca 3 , 470.Xr atexit 3 , 471.Xr getpagesize 3 , 472.Xr memory 3 , 473.Xr posix_memalign 3 474.Sh STANDARDS 475The 476.Fn malloc , 477.Fn calloc , 478.Fn realloc 479and 480.Fn free 481functions conform to 482.St -isoC . 483