1.\" $NetBSD: malloc.3,v 1.38 2010/05/03 08:23:20 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 21, 2010 38.Dt MALLOC 3 39.Os 40.Sh NAME 41.Nm malloc , 42.Nm calloc , 43.Nm realloc , 44.Nm reallocf , 45.Nm free 46.Nd general purpose memory allocation functions 47.Sh LIBRARY 48.Lb libc 49.Sh SYNOPSIS 50.In stdlib.h 51.Ft void * 52.Fn malloc "size_t size" 53.Ft void * 54.Fn calloc "size_t number" "size_t size" 55.Ft void * 56.Fn realloc "void *ptr" "size_t size" 57.Ft void * 58.Fn reallocf "void *ptr" "size_t size" 59.Ft void 60.Fn free "void *ptr" 61.Sh DESCRIPTION 62The 63.Fn malloc 64function allocates 65.Fa size 66bytes of uninitialized memory. 67The allocated space is suitably aligned (after possible pointer coercion) 68for storage of any type of object. 69If the space is at least 70.Em pagesize 71bytes in length (see 72.Xr getpagesize 3 ) , 73the returned memory will be page boundary aligned as well. 74.Pp 75The 76.Fn calloc 77function allocates space for 78.Fa number 79objects, 80each 81.Fa size 82bytes in length. 83The result is identical to calling 84.Fn malloc 85with an argument of 86.Dq "number * size" , 87with the exception that the allocated memory is explicitly initialized 88to zero bytes. 89.Pp 90The 91.Fn realloc 92function changes the size of the previously allocated memory referenced by 93.Fa ptr 94to 95.Fa size 96bytes. 97The contents of the memory are unchanged up to the lesser of the new and 98old sizes. 99If the new size is larger, 100the value of the newly allocated portion of the memory is undefined. 101Upon success, the memory referenced by 102.Fa ptr 103is freed and a pointer to the newly allocated memory is returned. 104Note that 105.Fn realloc 106may move the memory allocation, resulting in a different return value than 107.Fa ptr . 108If 109.Fa ptr 110is 111.Dv NULL , 112the 113.Fn realloc 114function behaves identically to 115.Fn malloc 116for the specified size. 117.Pp 118The 119.Fn reallocf 120function call is identical to the realloc function call, except that it 121will free the passed pointer when the requested memory cannot be allocated. 122This is a 123.Fx 124/ 125.Dx 126specific API designed to ease the problems with traditional coding styles 127for realloc causing memory leaks in libraries. 128.Pp 129The 130.Fn free 131function causes the allocated memory referenced by 132.Fa ptr 133to be made available for future allocations. 134If 135.Fa ptr 136is 137.Dv NULL , 138no action occurs. 139.Sh IMPLEMENTATION NOTES 140.Dx Ap s 141.Nm 142implementation is based on a port of the 143.Dx 144kernel slab allocator, appropriately modified for a user process 145environment. 146.Pp 147The slab allocator breaks memory allocations up to 8KB into 80 zones. 148Each zone represents a fixed allocation size in multiples of some 149core chunking. 150The chunking is a power-of-2 but the fixed allocation size is not. 151For example, a 1025-byte request is allocated out of the zone with a 152chunking of 128, thus in multiples of 1152 bytes. 153The minimum chunking, used for allocations in the 0-127 byte range, 154is 8 bytes (16 of the 80 zones). 155Beyond that the power-of-2 chunking is between 1/8 and 1/16 of the 156minimum allocation size for any given zone. 157.Pp 158As a special case any power-of-2-sized allocation within the zone 159limit (8K) will be aligned to the same power-of-2 rather than that 160zone's (smaller) chunking. 161This is not something you can depend upon for 162.Fn malloc , 163but it is used internally to optimize 164.Xr posix_memalign 3 . 165.Pp 166Each zone reserves memory in 64KB blocks. 167Actual memory use tends to be significantly less as only the pages 168actually needed are faulted in. 169Allocations larger than 8K are managed using 170.Xr mmap 2 171and tracked with a hash table. 172.Pp 173The zone mechanism results in well-fitted allocations with little 174waste in a long-running environment which makes a lot of allocations. 175Short-running environments which do not make many allocations will see 176a bit of extra bloat due to the large number of zones but it will 177be almost unnoticeable in the grand scheme of things. 178To reduce bloat further the normal randomized start offset implemented 179in the kernel version of the allocator to improve L1 cache fill is 180disabled in the libc version. 181.Pp 182The zone mechanism also has the nice side effect of greatly reducing 183fragmentation over the original 184.Nm . 185.Pp 186.Fn calloc 187is directly supported by keeping track of newly-allocated zones which 188will be demand-zero'd by the system. 189If the allocation is known to be zero'd we do not bother 190.Fn bzero Ns ing 191it. 192If it is a reused allocation we 193.Fn bzero . 194.Pp 195.Tn POSIX 196threading is supported by duplicating the primary structure. 197A thread entering 198.Fn malloc 199which is unable to immediately acquire a mutex on the last primary 200structure it used will switch to a different primary structure. 201At the moment this is more of a quick hack than a solution, but it works. 202.Sh RETURN VALUES 203The 204.Fn malloc 205and 206.Fn calloc 207functions return a pointer to the allocated memory if successful; otherwise 208a 209.Dv NULL 210pointer is returned and 211.Va errno 212is set to 213.Er ENOMEM . 214.Pp 215The 216.Fn realloc 217and 218.Fn reallocf 219functions return a pointer, possibly identical to 220.Fa ptr , 221to the allocated memory 222if successful; otherwise a 223.Dv NULL 224pointer is returned, and 225.Va errno 226is set to 227.Er ENOMEM 228if the error was the result of an allocation failure. 229The 230.Fn realloc 231function always leaves the original buffer intact 232when an error occurs, whereas 233.Fn reallocf 234deallocates it in this case. 235.Pp 236The 237.Fn free 238function returns no value. 239.Sh EXAMPLES 240When using 241.Fn malloc , 242be careful to avoid the following idiom: 243.Bd -literal -offset indent 244if ((p = malloc(number * size)) == NULL) 245 err(EXIT_FAILURE, "malloc"); 246.Ed 247.Pp 248The multiplication may lead to an integer overflow. 249To avoid this, 250.Fn calloc 251is recommended. 252.Pp 253If 254.Fn malloc 255must be used, be sure to test for overflow: 256.Bd -literal -offset indent 257if (size && number > SIZE_MAX / size) { 258 errno = EOVERFLOW; 259 err(EXIT_FAILURE, "allocation"); 260} 261.Ed 262.Pp 263When using 264.Fn realloc , 265one must be careful to avoid the following idiom: 266.Bd -literal -offset indent 267nsize += 50; 268 269if ((p = realloc(p, nsize)) == NULL) 270 return NULL; 271.Ed 272.Pp 273Do not adjust the variable describing how much memory has been allocated 274until it is known that the allocation has been successful. 275This can cause aberrant program behavior if the incorrect size value is used. 276In most cases, the above example will also leak memory. 277As stated earlier, a return value of 278.Dv NULL 279indicates that the old object still remains allocated. 280Better code looks like this: 281.Bd -literal -offset indent 282newsize = size + 50; 283 284if ((p2 = realloc(p, newsize)) == NULL) { 285 286 if (p != NULL) 287 free(p); 288 289 p = NULL; 290 return NULL; 291} 292 293p = p2; 294size = newsize; 295.Ed 296.Sh DIAGNOSTICS 297If 298.Fn malloc , 299.Fn calloc , 300.Fn realloc 301or 302.Fn free 303detect an error, a message will be printed to file descriptor 304.Dv STDERR_FILENO 305and the process will dump core. 306.Sh SEE ALSO 307.Xr madvise 2 , 308.Xr mmap 2 , 309.Xr sbrk 2 , 310.Xr alloca 3 , 311.Xr atexit 3 , 312.Xr emalloc 3 , 313.Xr getpagesize 3 , 314.Xr memory 3 , 315.Xr posix_memalign 3 316.Sh STANDARDS 317The 318.Fn malloc , 319.Fn calloc , 320.Fn realloc 321and 322.Fn free 323functions conform to 324.St -isoC . 325.Sh HISTORY 326The 327.Fn reallocf 328function first appeared in 329.Fx 3.0 . 330.Pp 331.Dx Ap s 332.Nm 333implementation is based on the kernel's slab allocator (see 334.Xr posix_memalign 3 Ap s 335.Sx IMPLEMENTATION NOTES ) . 336It first appeared in 337.Dx 2.3 . 338.Sh AUTHORS 339.An Matt Dillon 340