1.\" 2.\" Copyright (c) 1980, 1991, 1993 3.\" The Regents of the University of California. All rights reserved. 4.\" 5.\" This code is derived from software contributed to Berkeley by 6.\" the American National Standards Committee X3, on Information 7.\" Processing Systems. 8.\" 9.\" Redistribution and use in source and binary forms, with or without 10.\" modification, are permitted provided that the following conditions 11.\" are met: 12.\" 1. Redistributions of source code must retain the above copyright 13.\" notice, this list of conditions and the following disclaimer. 14.\" 2. Redistributions in binary form must reproduce the above copyright 15.\" notice, this list of conditions and the following disclaimer in the 16.\" documentation and/or other materials provided with the distribution. 17.\" 3. Neither the name of the University nor the names of its contributors 18.\" may be used to endorse or promote products derived from this software 19.\" without specific prior written permission. 20.\" 21.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 22.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 23.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 24.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 25.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 26.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 27.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 28.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 29.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 30.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31.\" SUCH DAMAGE. 32.\" 33.\" $OpenBSD: malloc.3,v 1.95 2016/04/03 09:31:45 otto Exp $ 34.\" 35.Dd $Mdocdate: April 3 2016 $ 36.Dt MALLOC 3 37.Os 38.Sh NAME 39.Nm malloc , 40.Nm calloc , 41.Nm reallocarray , 42.Nm realloc , 43.Nm free 44.Nd memory allocation and deallocation 45.Sh SYNOPSIS 46.In stdlib.h 47.Ft void * 48.Fn malloc "size_t size" 49.Ft void * 50.Fn calloc "size_t nmemb" "size_t size" 51.Ft void * 52.Fn reallocarray "void *ptr" "size_t nmemb" "size_t size" 53.Ft void * 54.Fn realloc "void *ptr" "size_t size" 55.Ft void 56.Fn free "void *ptr" 57.Vt char *malloc_options ; 58.Sh DESCRIPTION 59The 60.Fn malloc 61function allocates uninitialized space for an object of 62the specified 63.Fa size . 64.Fn malloc 65maintains multiple lists of free blocks according to size, allocating 66space from the appropriate list. 67The allocated space is suitably aligned (after possible pointer coercion) for 68storage of any type of object. 69If the space is of 70.Em pagesize 71or larger, the memory returned will be page-aligned. 72.Pp 73The 74.Fn calloc 75function allocates space for an array of 76.Fa nmemb 77objects, each of the specified 78.Fa size . 79The space is initialized to zero. 80.Pp 81The 82.Fn realloc 83function changes the size of the object pointed to by 84.Fa ptr 85to 86.Fa size 87bytes and returns a pointer to the (possibly moved) object. 88The contents of the object are unchanged up to the lesser 89of the new and old sizes. 90If the new size is larger, the value of the newly allocated portion 91of the object is indeterminate and uninitialized. 92If the space cannot be allocated, the object 93pointed to by 94.Fa ptr 95is unchanged. 96If 97.Fa ptr 98is 99.Dv NULL , 100.Fn realloc 101behaves like 102.Fn malloc 103and allocates a new object. 104.Pp 105The 106.Fn reallocarray 107function is similar to 108.Fn realloc 109except it operates on 110.Fa nmemb 111members of size 112.Fa size 113and checks for integer overflow in the calculation 114.Fa nmemb 115* 116.Fa size . 117.Pp 118The 119.Fn free 120function causes the space pointed to by 121.Fa ptr 122to be either placed on a list of free pages to make it available for future 123allocation or, if required, to be returned to the kernel using 124.Xr munmap 2 . 125If 126.Fa ptr 127is a 128.Dv NULL 129pointer, no action occurs. 130If 131.Fa ptr 132was previously freed by 133.Fn free , 134.Fn realloc , 135or 136.Fn reallocarray , 137the behavior is undefined and the double free is a security concern. 138.Sh RETURN VALUES 139Upon successful completion, the functions 140.Fn malloc , 141.Fn calloc , 142.Fn realloc , 143and 144.Fn reallocarray 145return a pointer to the allocated space; otherwise, a 146.Dv NULL 147pointer is returned and 148.Va errno 149is set to 150.Er ENOMEM . 151.Pp 152If 153.Fa size 154or 155.Fa nmemb 156is equal to 0, a unique pointer to an access protected, 157zero sized object is returned. 158Access via this pointer will generate a 159.Dv SIGSEGV 160exception. 161.Pp 162If multiplying 163.Fa nmemb 164and 165.Fa size 166results in integer overflow, 167.Fn calloc 168and 169.Fn reallocarray 170return 171.Dv NULL 172and set 173.Va errno 174to 175.Er ENOMEM . 176.Sh IDIOMS 177Consider 178.Fn calloc 179or the extension 180.Fn reallocarray 181when there is multiplication in the 182.Fa size 183argument of 184.Fn malloc 185or 186.Fn realloc . 187For example, avoid this common idiom as it may lead to integer overflow: 188.Bd -literal -offset indent 189if ((p = malloc(num * size)) == NULL) 190 err(1, NULL); 191.Ed 192.Pp 193A drop-in replacement is the 194.Ox 195extension 196.Fn reallocarray : 197.Bd -literal -offset indent 198if ((p = reallocarray(NULL, num, size)) == NULL) 199 err(1, NULL); 200.Ed 201.Pp 202Alternatively, 203.Fn calloc 204may be used at the cost of initialization overhead. 205.Pp 206When using 207.Fn realloc , 208be careful to avoid the following idiom: 209.Bd -literal -offset indent 210size += 50; 211if ((p = realloc(p, size)) == NULL) 212 return (NULL); 213.Ed 214.Pp 215Do not adjust the variable describing how much memory has been allocated 216until the allocation has been successful. 217This can cause aberrant program behavior if the incorrect size value is used. 218In most cases, the above sample will also result in a leak of memory. 219As stated earlier, a return value of 220.Dv NULL 221indicates that the old object still remains allocated. 222Better code looks like this: 223.Bd -literal -offset indent 224newsize = size + 50; 225if ((newp = realloc(p, newsize)) == NULL) { 226 free(p); 227 p = NULL; 228 size = 0; 229 return (NULL); 230} 231p = newp; 232size = newsize; 233.Ed 234.Pp 235As with 236.Fn malloc , 237it is important to ensure the new size value will not overflow; 238i.e. avoid allocations like the following: 239.Bd -literal -offset indent 240if ((newp = realloc(p, num * size)) == NULL) { 241 ... 242.Ed 243.Pp 244Instead, use 245.Fn reallocarray : 246.Bd -literal -offset indent 247if ((newp = reallocarray(p, num, size)) == NULL) { 248 ... 249.Ed 250.Pp 251Calling 252.Fn realloc 253with a 254.Dv NULL 255.Fa ptr 256is equivalent to calling 257.Fn malloc . 258Instead of this idiom: 259.Bd -literal -offset indent 260if (p == NULL) 261 newp = malloc(newsize); 262else 263 newp = realloc(p, newsize); 264.Ed 265.Pp 266Use the following: 267.Bd -literal -offset indent 268newp = realloc(p, newsize); 269.Ed 270.Sh ENVIRONMENT 271.Bl -tag -width "/etc/malloc.conf" 272.It Ev MALLOC_OPTIONS 273String of flags documented in 274.Xr malloc.conf 5 . 275.El 276.Sh FILES 277.Bl -tag -width "/etc/malloc.conf" 278.It Pa /etc/malloc.conf 279Symbolic link to filename containing option flags. 280.El 281.Sh EXAMPLES 282If 283.Fn malloc 284must be used with multiplication, be sure to test for overflow: 285.Bd -literal -offset indent 286size_t num, size; 287\&... 288 289/* Check for size_t overflow */ 290if (size && num > SIZE_MAX / size) 291 errc(1, EOVERFLOW, "overflow"); 292 293if ((p = malloc(size * num)) == NULL) 294 err(1, NULL); 295.Ed 296.Pp 297The above test is not sufficient in all cases. 298For example, multiplying ints requires a different set of checks: 299.Bd -literal -offset indent 300int num, size; 301\&... 302 303/* Avoid invalid requests */ 304if (size < 0 || num < 0) 305 errc(1, EOVERFLOW, "overflow"); 306 307/* Check for signed int overflow */ 308if (size && num > INT_MAX / size) 309 errc(1, EOVERFLOW, "overflow"); 310 311if ((p = malloc(size * num)) == NULL) 312 err(1, NULL); 313.Ed 314.Pp 315Assuming the implementation checks for integer overflow as 316.Ox 317does, it is much easier to use 318.Fn calloc 319or 320.Fn reallocarray . 321.Pp 322The above examples could be simplified to: 323.Bd -literal -offset indent 324if ((p = reallocarray(NULL, num, size)) == NULL) 325 err(1, NULL); 326.Ed 327.Pp 328or at the cost of initialization: 329.Bd -literal -offset indent 330if ((p = calloc(num, size)) == NULL) 331 err(1, NULL); 332.Ed 333.Sh DIAGNOSTICS 334If 335.Fn malloc , 336.Fn calloc , 337.Fn realloc , 338.Fn reallocarray , 339or 340.Fn free 341detect an error condition, 342a message will be printed to file descriptor 3432 (not using stdio). 344Errors will result in the process being aborted. 345.Pp 346Here is a brief description of the error messages and what they mean: 347.Bl -tag -width Ds 348.It Dq out of memory 349If the 350.Cm X 351option is specified it is an error for 352.Fn malloc , 353.Fn calloc , 354.Fn realloc , 355or 356.Fn reallocarray 357to return 358.Dv NULL . 359.It Dq malloc init mmap failed 360This is a rather weird condition that is most likely to indicate a 361seriously overloaded system or a ulimit restriction. 362.It Dq bogus pointer (double free?) 363An attempt to 364.Fn free , 365.Fn realloc , 366or 367.Fn reallocarray 368an unallocated pointer was made. 369.It Dq chunk is already free 370There was an attempt to free a chunk that had already been freed. 371.It Dq use after free 372A chunk has been modified after it was freed. 373.It Dq modified chunk-pointer 374The pointer passed to 375.Fn free , 376.Fn realloc , 377or 378.Fn reallocarray 379has been modified. 380.It Dq recursive call 381An attempt was made to call recursively into these functions, i.e., from a 382signal handler. 383This behavior is not supported. 384In particular, signal handlers should 385.Em not 386use any of the 387.Fn malloc 388functions nor utilize any other functions which may call 389.Fn malloc 390(e.g., 391.Xr stdio 3 392routines). 393.It Dq unknown char in MALLOC_OPTIONS 394We found something we didn't understand. 395.It Dq malloc cache overflow/underflow 396The internal malloc page cache has been corrupted. 397.It Dq malloc free slot lost 398The internal malloc page cache has been corrupted. 399.It Dq guard size 400An inconsistent guard size was detected. 401.It any other error 402.Fn malloc 403detected an internal error; 404consult sources and/or wizards. 405.El 406.Sh SEE ALSO 407.Xr brk 2 , 408.Xr mmap 2 , 409.Xr munmap 2 , 410.Xr alloca 3 , 411.Xr getpagesize 3 , 412.Xr posix_memalign 3 , 413.Xr sysconf 3 , 414.Xr malloc.conf 5 415.Sh STANDARDS 416The 417.Fn malloc , 418.Fn calloc , 419.Fn realloc , 420and 421.Fn free 422functions conform to 423.St -ansiC . 424.Pp 425If 426.Fa size 427or 428.Fa nmemb 429are 0, the return value is implementation defined; 430other conforming implementations may return 431.Dv NULL 432in this case. 433.Pp 434The 435.Ev MALLOC_OPTIONS 436environment variable, the file 437.Pa /etc/malloc.conf , 438and the 439.Sx DIAGNOSTICS 440output are extensions to the standard. 441.Sh HISTORY 442A 443.Fn free 444internal kernel function and a predecessor to 445.Fn malloc , 446.Fn alloc , 447first appeared in 448.At v1 . 449C library functions 450.Fn alloc 451and 452.Fn free 453appeared in 454.At v6 . 455The functions 456.Fn malloc , 457.Fn calloc , 458and 459.Fn realloc 460first appeared in 461.At v7 . 462.Pp 463A new implementation by Chris Kingsley was introduced in 464.Bx 4.2 , 465followed by a complete rewrite by Poul-Henning Kamp which appeared in 466.Fx 2.2 467and was included in 468.Ox 2.0 . 469These implementations were all 470.Xr sbrk 2 471based. 472In 473.Ox 3.8 , 474Thierry Deval rewrote 475.Nm 476to use the 477.Xr mmap 2 478system call, 479making the page addresses returned by 480.Nm 481random. 482A rewrite by Otto Moerbeek introducing a new central data structure and more 483randomization appeared in 484.Ox 4.4 . 485.Pp 486The 487.Fn reallocarray 488function appeared in 489.Ox 5.6 . 490.Sh CAVEATS 491When using 492.Fn malloc , 493be wary of signed integer and 494.Vt size_t 495overflow especially when there is multiplication in the 496.Fa size 497argument. 498.Pp 499Signed integer overflow will cause undefined behavior which compilers 500typically handle by wrapping back around to negative numbers. 501Depending on the input, this can result in allocating more or less 502memory than intended. 503.Pp 504An unsigned overflow has defined behavior which will wrap back around and 505return less memory than intended. 506.Pp 507A signed or unsigned integer overflow is a 508.Em security 509risk if less memory is returned than intended. 510Subsequent code may corrupt the heap by writing beyond the memory that was 511allocated. 512An attacker may be able to leverage this heap corruption to execute arbitrary 513code. 514.Pp 515Consider using 516.Fn calloc 517or 518.Fn reallocarray 519instead of using multiplication in 520.Fn malloc 521and 522.Fn realloc 523to avoid these problems on 524.Ox . 525