1.\" $NetBSD: malloc.3,v 1.30 2009/07/20 12:10:03 pooka 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 June 20, 2009 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 81The 82.Fn realloc 83function changes the size of the previously allocated memory referenced by 84.Fa ptr 85to 86.Fa size 87bytes. 88The contents of the memory are unchanged up to the lesser of the new and 89old sizes. 90If the new size is larger, 91the value of the newly allocated portion of the memory is undefined. 92Upon success, the memory referenced by 93.Fa ptr 94is freed and a pointer to the newly allocated memory is returned. 95Note that 96.Fn realloc 97may move the memory allocation, resulting in a different return value than 98.Fa ptr . 99If 100.Fa ptr 101is 102.Dv NULL , 103the 104.Fn realloc 105function behaves identically to 106.Fn malloc 107for the specified size. 108.Pp 109When using 110.Fn realloc 111one must be careful to avoid the following idiom: 112.Pp 113.Bd -literal -offset indent 114nsize += 50; 115if ((p = realloc(p, nsize)) == NULL) 116 return (NULL); 117.Ed 118.Pp 119Do not adjust the variable describing how much memory has been allocated 120until one knows the allocation has been successful. 121This can cause aberrant program behavior if the incorrect size value is used. 122In most cases, the above sample will also result in a leak of memory. 123As stated earlier, a return value of 124.Dv NULL 125indicates that the old object still remains allocated. 126Better code looks like this: 127.Bd -literal -offset indent 128newsize = size + 50; 129if ((p2 = realloc(p, newsize)) == NULL) { 130 if (p) 131 free(p); 132 p = NULL; 133 return (NULL); 134} 135p = p2; 136size = newsize; 137.Ed 138.Pp 139The 140.Fn free 141function causes the allocated memory referenced by 142.Fa ptr 143to be made available for future allocations. 144If 145.Fa ptr 146is 147.Dv NULL , 148no action occurs. 149.Sh TUNING 150Once, when the first call is made to one of these memory allocation 151routines, various flags will be set or reset, which affect the 152workings of this allocator implementation. 153.Pp 154The 155.Dq name 156of the file referenced by the symbolic link named 157.Pa /etc/malloc.conf , 158the value of the environment variable 159.Ev MALLOC_OPTIONS , 160and the string pointed to by the global variable 161.Va _malloc_options 162will be interpreted, in that order, character by character as flags. 163.Pp 164Most flags are single letters, 165where uppercase indicates that the behavior is set, or on, 166and lowercase means that the behavior is not set, or off. 167.Bl -tag -width indent 168.It A 169All warnings (except for the warning about unknown 170flags being set) become fatal. 171The process will call 172.Xr abort 3 173in these cases. 174.It H 175Use 176.Xr madvise 2 177when pages within a chunk are no longer in use, but the chunk as a whole cannot 178yet be deallocated. 179This is primarily of use when swapping is a real possibility, due to the high 180overhead of the 181.Fn madvise 182system call. 183.It J 184Each byte of new memory allocated by 185.Fn malloc , 186.Fn realloc 187will be initialized to 0xa5. 188All memory returned by 189.Fn free , 190.Fn realloc 191will be initialized to 0x5a. 192This is intended for debugging and will impact performance negatively. 193.It K 194Increase/decrease the virtual memory chunk size by a factor of two. 195The default chunk size is 1 MB. 196This option can be specified multiple times. 197.It N 198Increase/decrease the number of arenas by a factor of two. 199The default number of arenas is four times the number of CPUs, or one if there 200is a single CPU. 201This option can be specified multiple times. 202.It P 203Various statistics are printed at program exit via an 204.Xr atexit 3 205function. 206This has the potential to cause deadlock for a multi-threaded process that exits 207while one or more threads are executing in the memory allocation functions. 208Therefore, this option should only be used with care; it is primarily intended 209as a performance tuning aid during application development. 210.It Q 211Increase/decrease the size of the allocation quantum by a factor of two. 212The default quantum is the minimum allowed by the architecture (typically 8 or 21316 bytes). 214This option can be specified multiple times. 215.It S 216Increase/decrease the size of the maximum size class that is a multiple of the 217quantum by a factor of two. 218Above this size, power-of-two spacing is used for size classes. 219The default value is 512 bytes. 220This option can be specified multiple times. 221.It U 222Generate 223.Dq utrace 224entries for 225.Xr ktrace 1 , 226for all operations. 227Consult the source for details on this option. 228.It V 229Attempting to allocate zero bytes will return a 230.Dv NULL 231pointer instead of a valid pointer. 232(The default behavior is to make a minimal allocation and return a 233pointer to it.) 234This option is provided for System V compatibility. 235This option is incompatible with the 236.Dq X 237option. 238.It X 239Rather than return failure for any allocation function, 240display a diagnostic message on 241.Dv stderr 242and cause the program to drop 243core (using 244.Xr abort 3 ) . 245This option should be set at compile time by including the following in 246the source code: 247.Bd -literal -offset indent 248_malloc_options = "X"; 249.Ed 250.It Z 251Each byte of new memory allocated by 252.Fn malloc , 253.Fn realloc 254will be initialized to 0. 255Note that this initialization only happens once for each byte, so 256.Fn realloc 257does not zero memory that was previously allocated. 258This is intended for debugging and will impact performance negatively. 259.El 260.Pp 261The 262.Dq J 263and 264.Dq Z 265options are intended for testing and debugging. 266An application which changes its behavior when these options are used 267is flawed. 268.Sh IMPLEMENTATION NOTES 269This allocator uses multiple arenas in order to reduce lock contention for 270threaded programs on multi-processor systems. 271This works well with regard to threading scalability, but incurs some costs. 272There is a small fixed per-arena overhead, and additionally, arenas manage 273memory completely independently of each other, which means a small fixed 274increase in overall memory fragmentation. 275These overheads are not generally an issue, given the number of arenas normally 276used. 277Note that using substantially more arenas than the default is not likely to 278improve performance, mainly due to reduced cache performance. 279However, it may make sense to reduce the number of arenas if an application 280does not make much use of the allocation functions. 281.Pp 282Memory is conceptually broken into equal-sized chunks, where the chunk size is 283a power of two that is greater than the page size. 284Chunks are always aligned to multiples of the chunk size. 285This alignment makes it possible to find metadata for user objects very 286quickly. 287.Pp 288User objects are broken into three categories according to size: small, large, 289and huge. 290Small objects are no larger than one half of a page. 291Large objects are smaller than the chunk size. 292Huge objects are a multiple of the chunk size. 293Small and large objects are managed by arenas; huge objects are managed 294separately in a single data structure that is shared by all threads. 295Huge objects are used by applications infrequently enough that this single 296data structure is not a scalability issue. 297.Pp 298Each chunk that is managed by an arena tracks its contents in a page map as 299runs of contiguous pages (unused, backing a set of small objects, or backing 300one large object). 301The combination of chunk alignment and chunk page maps makes it possible to 302determine all metadata regarding small and large allocations in constant time. 303.Pp 304Small objects are managed in groups by page runs. 305Each run maintains a bitmap that tracks which regions are in use. 306Allocation requests that are no more than half the quantum (see the 307.Dq Q 308option) are rounded up to the nearest power of two (typically 2, 4, or 8). 309Allocation requests that are more than half the quantum, but no more than the 310maximum quantum-multiple size class (see the 311.Dq S 312option) are rounded up to the nearest multiple of the quantum. 313Allocation requests that are larger than the maximum quantum-multiple size 314class, but no larger than one half of a page, are rounded up to the nearest 315power of two. 316Allocation requests that are larger than half of a page, but small enough to 317fit in an arena-managed chunk (see the 318.Dq K 319option), are rounded up to the nearest run size. 320Allocation requests that are too large to fit in an arena-managed chunk are 321rounded up to the nearest multiple of the chunk size. 322.Pp 323Allocations are packed tightly together, which can be an issue for 324multi-threaded applications. 325If you need to assure that allocations do not suffer from cache line sharing, 326round your allocation requests up to the nearest multiple of the cache line 327size. 328.Sh DEBUGGING MALLOC PROBLEMS 329The first thing to do is to set the 330.Dq A 331option. 332This option forces a coredump (if possible) at the first sign of trouble, 333rather than the normal policy of trying to continue if at all possible. 334.Pp 335It is probably also a good idea to recompile the program with suitable 336options and symbols for debugger support. 337.Pp 338If the program starts to give unusual results, coredump or generally behave 339differently without emitting any of the messages mentioned in the next 340section, it is likely because it depends on the storage being filled with 341zero bytes. 342Try running it with the 343.Dq Z 344option set; 345if that improves the situation, this diagnosis has been confirmed. 346If the program still misbehaves, 347the likely problem is accessing memory outside the allocated area. 348.Pp 349Alternatively, if the symptoms are not easy to reproduce, setting the 350.Dq J 351option may help provoke the problem. 352.Pp 353In truly difficult cases, the 354.Dq U 355option, if supported by the kernel, can provide a detailed trace of 356all calls made to these functions. 357.Pp 358Unfortunately this implementation does not provide much detail about 359the problems it detects; the performance impact for storing such information 360would be prohibitive. 361There are a number of allocator implementations available on the Internet 362which focus on detecting and pinpointing problems by trading performance for 363extra sanity checks and detailed diagnostics. 364.Sh DIAGNOSTIC MESSAGES 365If any of the memory allocation/deallocation functions detect an error or 366warning condition, a message will be printed to file descriptor 367.Dv STDERR_FILENO . 368Errors will result in the process dumping core. 369If the 370.Dq A 371option is set, all warnings are treated as errors. 372.Pp 373The 374.Va _malloc_message 375variable allows the programmer to override the function which emits 376the text strings forming the errors and warnings if for some reason 377the 378.Dv stderr 379file descriptor is not suitable for this. 380Please note that doing anything which tries to allocate memory in 381this function is likely to result in a crash or deadlock. 382.Pp 383All messages are prefixed by 384.Dq Ao Ar progname Ac Ns Li \&: Pq malloc . 385.Sh RETURN VALUES 386The 387.Fn malloc 388and 389.Fn calloc 390functions return a pointer to the allocated memory if successful; otherwise 391a 392.Dv NULL 393pointer is returned and 394.Va errno 395is set to 396.Er ENOMEM . 397.Pp 398The 399.Fn realloc 400function returns a pointer, possibly identical to 401.Fa ptr , 402to the allocated memory 403if successful; otherwise a 404.Dv NULL 405pointer is returned, and 406.Va errno 407is set to 408.Er ENOMEM 409if the error was the result of an allocation failure. 410The 411.Fn realloc 412function always leaves the original buffer intact 413when an error occurs. 414.Pp 415The 416.Fn free 417function returns no value. 418.Sh ENVIRONMENT 419The following environment variables affect the execution of the allocation 420functions: 421.Bl -tag -width ".Ev MALLOC_OPTIONS" 422.It Ev MALLOC_OPTIONS 423If the environment variable 424.Ev MALLOC_OPTIONS 425is set, the characters it contains will be interpreted as flags to the 426allocation functions. 427.El 428.Sh EXAMPLES 429To dump core whenever a problem occurs: 430.Pp 431.Bd -literal -offset indent 432ln -s 'A' /etc/malloc.conf 433.Ed 434.Pp 435To specify in the source that a program does no return value checking 436on calls to these functions: 437.Bd -literal -offset indent 438_malloc_options = "X"; 439.Ed 440.Sh SEE ALSO 441.\" .Xr limits 1 , 442.Xr madvise 2 , 443.Xr mmap 2 , 444.Xr sbrk 2 , 445.Xr alloca 3 , 446.Xr atexit 3 , 447.Xr getpagesize 3 , 448.Xr memory 3 , 449.Xr posix_memalign 3 450.Sh STANDARDS 451The 452.Fn malloc , 453.Fn calloc , 454.Fn realloc 455and 456.Fn free 457functions conform to 458.St -isoC . 459