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