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.100 2016/10/20 08:03:15 jmc Exp $ 34.\" 35.Dd $Mdocdate: October 20 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 chunk canary corrupted address offset@length 381A byte after the requested size has been overwritten, 382indicating a heap overflow. 383The offset at which corruption was detected is printed before the @, 384and the requested length of the allocation after the @. 385.It Dq recursive call 386An attempt was made to call recursively into these functions, i.e., from a 387signal handler. 388This behavior is not supported. 389In particular, signal handlers should 390.Em not 391use any of the 392.Fn malloc 393functions nor utilize any other functions which may call 394.Fn malloc 395(e.g., 396.Xr stdio 3 397routines). 398.It Dq unknown char in MALLOC_OPTIONS 399We found something we didn't understand. 400.It Dq malloc cache overflow/underflow 401The internal malloc page cache has been corrupted. 402.It Dq malloc free slot lost 403The internal malloc page cache has been corrupted. 404.It Dq guard size 405An inconsistent guard size was detected. 406.It any other error 407.Fn malloc 408detected an internal error; 409consult sources and/or wizards. 410.El 411.Sh SEE ALSO 412.Xr brk 2 , 413.Xr mmap 2 , 414.Xr munmap 2 , 415.Xr alloca 3 , 416.Xr getpagesize 3 , 417.Xr posix_memalign 3 , 418.Xr sysconf 3 , 419.Xr malloc.conf 5 420.Sh STANDARDS 421The 422.Fn malloc , 423.Fn calloc , 424.Fn realloc , 425and 426.Fn free 427functions conform to 428.St -ansiC . 429.Pp 430If 431.Fa size 432or 433.Fa nmemb 434are 0, the return value is implementation defined; 435other conforming implementations may return 436.Dv NULL 437in this case. 438.Pp 439The 440.Ev MALLOC_OPTIONS 441environment variable, the file 442.Pa /etc/malloc.conf , 443and the 444.Sx DIAGNOSTICS 445output are extensions to the standard. 446.Sh HISTORY 447A 448.Fn free 449internal kernel function and a predecessor to 450.Fn malloc , 451.Fn alloc , 452first appeared in 453.At v1 . 454C library functions 455.Fn alloc 456and 457.Fn free 458appeared in 459.At v6 . 460The functions 461.Fn malloc , 462.Fn calloc , 463and 464.Fn realloc 465first appeared in 466.At v7 . 467.Pp 468A new implementation by Chris Kingsley was introduced in 469.Bx 4.2 , 470followed by a complete rewrite by Poul-Henning Kamp which appeared in 471.Fx 2.2 472and was included in 473.Ox 2.0 . 474These implementations were all 475.Xr sbrk 2 476based. 477In 478.Ox 3.8 , 479Thierry Deval rewrote 480.Nm 481to use the 482.Xr mmap 2 483system call, 484making the page addresses returned by 485.Nm 486random. 487A rewrite by Otto Moerbeek introducing a new central data structure and more 488randomization appeared in 489.Ox 4.4 . 490.Pp 491The 492.Fn reallocarray 493function appeared in 494.Ox 5.6 . 495.Sh CAVEATS 496When using 497.Fn malloc , 498be wary of signed integer and 499.Vt size_t 500overflow especially when there is multiplication in the 501.Fa size 502argument. 503.Pp 504Signed integer overflow will cause undefined behavior which compilers 505typically handle by wrapping back around to negative numbers. 506Depending on the input, this can result in allocating more or less 507memory than intended. 508.Pp 509An unsigned overflow has defined behavior which will wrap back around and 510return less memory than intended. 511.Pp 512A signed or unsigned integer overflow is a 513.Em security 514risk if less memory is returned than intended. 515Subsequent code may corrupt the heap by writing beyond the memory that was 516allocated. 517An attacker may be able to leverage this heap corruption to execute arbitrary 518code. 519.Pp 520Consider using 521.Fn calloc 522or 523.Fn reallocarray 524instead of using multiplication in 525.Fn malloc 526and 527.Fn realloc 528to avoid these problems on 529.Ox . 530