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.115 2017/05/15 18:05:34 tb Exp $ 34.\" 35.Dd $Mdocdate: May 15 2017 $ 36.Dt MALLOC 3 37.Os 38.Sh NAME 39.Nm malloc , 40.Nm calloc , 41.Nm realloc , 42.Nm free , 43.Nm reallocarray , 44.Nm recallocarray , 45.Nm freezero 46.Nd memory allocation and deallocation 47.Sh SYNOPSIS 48.In stdlib.h 49.Ft void * 50.Fn malloc "size_t size" 51.Ft void * 52.Fn calloc "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.Ft void * 58.Fn reallocarray "void *ptr" "size_t nmemb" "size_t size" 59.Ft void * 60.Fn recallocarray "void *ptr" "size_t oldnmemb" "size_t nmemb" "size_t size" 61.Ft void 62.Fn freezero "void *ptr" "size_t size" 63.Vt char *malloc_options ; 64.Sh DESCRIPTION 65The standard functions 66.Fn malloc , 67.Fn calloc , 68and 69.Fn realloc 70allocate 71.Em objects , 72regions of memory to store values. 73The 74.Fn malloc 75function allocates uninitialized space for an object of 76the specified 77.Fa size . 78.Fn malloc 79maintains multiple lists of free objects according to size, allocating 80from the appropriate list or requesting memory from the kernel. 81The allocated space is suitably aligned (after possible pointer coercion) for 82storage of any type of object. 83.Pp 84The 85.Fn calloc 86function allocates space for an array of 87.Fa nmemb 88objects, each of the specified 89.Fa size . 90The space is initialized to zero. 91.Pp 92The 93.Fn realloc 94function changes the size of the object pointed to by 95.Fa ptr 96to 97.Fa size 98bytes and returns a pointer to the (possibly moved) object. 99If 100.Fa ptr 101is not 102.Dv NULL , 103it must be a pointer returned by an earlier call to an allocation or 104reallocation function that was not freed in between. 105The contents of the object are unchanged up to the lesser 106of the new and old sizes. 107If the new size is larger, the value of the newly allocated portion 108of the object is indeterminate and uninitialized. 109If the space cannot be allocated, the object 110pointed to by 111.Fa ptr 112is unchanged. 113If 114.Fa ptr 115is 116.Dv NULL , 117.Fn realloc 118behaves like 119.Fn malloc 120and allocates a new object. 121.Pp 122The 123.Fn free 124function causes the space pointed to by 125.Fa ptr 126to be either placed on a list of free blocks to make it available for future 127allocation or, when appropriate, to be returned to the kernel using 128.Xr munmap 2 . 129If 130.Fa ptr 131is 132.Dv NULL , 133no action occurs. 134If 135.Fa ptr 136was previously freed by 137.Fn free 138or a reallocation function, 139the behavior is undefined and the double free is a security concern. 140.Pp 141Designed for safe allocation of arrays, 142the 143.Fn reallocarray 144function is similar to 145.Fn realloc 146except it operates on 147.Fa nmemb 148members of size 149.Fa size 150and checks for integer overflow in the calculation 151.Fa nmemb 152* 153.Fa size . 154.Pp 155Used for the allocation of memory holding sensitive data, 156the 157.Fn recallocarray 158and 159.Fn freezero 160functions guarantee that memory becoming unallocated is explicitly 161.Em discarded , 162meaning pages of memory are disposed via 163.Xr munmap 2 164and cached free objects are cleared with 165.Xr explicit_bzero 3 . 166.Pp 167The 168.Fn recallocarray 169function is similar to 170.Fn reallocarray 171except it ensures newly allocated memory is cleared similar to 172.Fn calloc . 173If 174.Fa ptr 175is 176.Dv NULL , 177.Fa oldnmemb 178is ignored and the call is equivalent to 179.Fn calloc . 180If 181.Fa ptr 182is not 183.Dv NULL , 184.Fa oldnmemb 185must be a value such that 186.Fa oldnmemb 187* 188.Fa size 189is the size of the earlier allocation that returned 190.Fa ptr , 191otherwise the behaviour is undefined. 192.Pp 193The 194.Fn freezero 195function is similar to the 196.Fn free 197function except it ensures memory is explicitly discarded. 198If 199.Fa ptr 200is 201.Dv NULL , 202no action occurs. 203If 204.Fa ptr 205is not 206.Dv NULL , 207the 208.Fa size 209argument must be equal or smaller than the size of the earlier allocation 210that returned 211.Fa ptr . 212.Fn freezero 213guarantees the memory range starting at 214.Fa ptr 215with length 216.Fa size 217is discarded while deallocating the whole object originally allocated. 218.Sh RETURN VALUES 219Upon successful completion, the allocation functions 220return a pointer to the allocated space; otherwise, 221.Dv NULL 222is returned and 223.Va errno 224is set to 225.Er ENOMEM . 226.Pp 227If 228.Fa nmemb 229or 230.Fa size 231is equal to 0, a unique pointer to an access protected, 232zero sized object is returned. 233Access via this pointer will generate a 234.Dv SIGSEGV 235exception. 236.Pp 237If multiplying 238.Fa nmemb 239and 240.Fa size 241results in integer overflow, 242.Fn calloc , 243.Fn reallocarray 244and 245.Fn recallocarray 246return 247.Dv NULL 248and set 249.Va errno 250to 251.Er ENOMEM . 252.Pp 253If 254.Fa ptr 255is not 256.Dv NULL 257and multiplying 258.Fa oldnmemb 259and 260.Fa size 261results in integer overflow 262.Fn recallocarray 263returns 264.Dv NULL 265and sets 266.Va errno 267to 268.Er EINVAL . 269.Sh IDIOMS 270Consider 271.Fn calloc 272or the extensions 273.Fn reallocarray 274and 275.Fn recallocarray 276when there is multiplication in the 277.Fa size 278argument of 279.Fn malloc 280or 281.Fn realloc . 282For example, avoid this common idiom as it may lead to integer overflow: 283.Bd -literal -offset indent 284if ((p = malloc(num * size)) == NULL) 285 err(1, NULL); 286.Ed 287.Pp 288A drop-in replacement is the 289.Ox 290extension 291.Fn reallocarray : 292.Bd -literal -offset indent 293if ((p = reallocarray(NULL, num, size)) == NULL) 294 err(1, NULL); 295.Ed 296.Pp 297Alternatively, 298.Fn calloc 299may be used at the cost of initialization overhead. 300.Pp 301When using 302.Fn realloc , 303be careful to avoid the following idiom: 304.Bd -literal -offset indent 305size += 50; 306if ((p = realloc(p, size)) == NULL) 307 return (NULL); 308.Ed 309.Pp 310Do not adjust the variable describing how much memory has been allocated 311until the allocation has been successful. 312This can cause aberrant program behavior if the incorrect size value is used. 313In most cases, the above sample will also result in a leak of memory. 314As stated earlier, a return value of 315.Dv NULL 316indicates that the old object still remains allocated. 317Better code looks like this: 318.Bd -literal -offset indent 319newsize = size + 50; 320if ((newp = realloc(p, newsize)) == NULL) { 321 free(p); 322 p = NULL; 323 size = 0; 324 return (NULL); 325} 326p = newp; 327size = newsize; 328.Ed 329.Pp 330As with 331.Fn malloc , 332it is important to ensure the new size value will not overflow; 333i.e. avoid allocations like the following: 334.Bd -literal -offset indent 335if ((newp = realloc(p, num * size)) == NULL) { 336 ... 337.Ed 338.Pp 339Instead, use 340.Fn reallocarray : 341.Bd -literal -offset indent 342if ((newp = reallocarray(p, num, size)) == NULL) { 343 ... 344.Ed 345.Pp 346Calling 347.Fn realloc 348with a 349.Dv NULL 350.Fa ptr 351is equivalent to calling 352.Fn malloc . 353Instead of this idiom: 354.Bd -literal -offset indent 355if (p == NULL) 356 newp = malloc(newsize); 357else 358 newp = realloc(p, newsize); 359.Ed 360.Pp 361Use the following: 362.Bd -literal -offset indent 363newp = realloc(p, newsize); 364.Ed 365.Pp 366The 367.Fn recallocarray 368function should be used for resizing objects containing sensitive data like 369keys. 370To avoid leaking information, 371it guarantees memory is cleared before placing it on the internal free list. 372Deallocation of such an object should be done by calling 373.Fn freezero . 374.Sh ENVIRONMENT 375.Bl -tag -width "/etc/malloc.conf" 376.It Ev MALLOC_OPTIONS 377String of flags documented in 378.Xr malloc.conf 5 . 379.El 380.Sh FILES 381.Bl -tag -width "/etc/malloc.conf" 382.It Pa /etc/malloc.conf 383Symbolic link to filename containing option flags. 384.El 385.Sh EXAMPLES 386If 387.Fn malloc 388must be used with multiplication, be sure to test for overflow: 389.Bd -literal -offset indent 390size_t num, size; 391\&... 392 393/* Check for size_t overflow */ 394if (size && num > SIZE_MAX / size) 395 errc(1, EOVERFLOW, "overflow"); 396 397if ((p = malloc(num * size)) == NULL) 398 err(1, NULL); 399.Ed 400.Pp 401The above test is not sufficient in all cases. 402For example, multiplying ints requires a different set of checks: 403.Bd -literal -offset indent 404int num, size; 405\&... 406 407/* Avoid invalid requests */ 408if (size < 0 || num < 0) 409 errc(1, EOVERFLOW, "overflow"); 410 411/* Check for signed int overflow */ 412if (size && num > INT_MAX / size) 413 errc(1, EOVERFLOW, "overflow"); 414 415if ((p = malloc(num * size)) == NULL) 416 err(1, NULL); 417.Ed 418.Pp 419Assuming the implementation checks for integer overflow as 420.Ox 421does, it is much easier to use 422.Fn calloc , 423.Fn reallocarray , 424or 425.Fn recallocarray . 426.Pp 427The above examples could be simplified to: 428.Bd -literal -offset indent 429if ((p = reallocarray(NULL, num, size)) == NULL) 430 err(1, NULL); 431.Ed 432.Pp 433or at the cost of initialization: 434.Bd -literal -offset indent 435if ((p = calloc(num, size)) == NULL) 436 err(1, NULL); 437.Ed 438.Sh DIAGNOSTICS 439If any of the functions detect an error condition, 440a message will be printed to file descriptor 4412 (not using stdio). 442Errors will result in the process being aborted. 443.Pp 444Here is a brief description of the error messages and what they mean: 445.Bl -tag -width Ds 446.It Dq out of memory 447If the 448.Cm X 449option is specified it is an error for the allocation functions 450to return 451.Dv NULL . 452.It Dq bogus pointer (double free?) 453An attempt to 454.Fn free 455or 456reallocate an unallocated pointer was made. 457.It Dq chunk is already free 458There was an attempt to free a chunk that had already been freed. 459.It Dq use after free 460A chunk has been modified after it was freed. 461.It Dq modified chunk-pointer 462The pointer passed to 463.Fn free 464or a reallocation function has been modified. 465.It Dq chunk canary corrupted address offset@length 466A byte after the requested size has been overwritten, 467indicating a heap overflow. 468The offset at which corruption was detected is printed before the @, 469and the requested length of the allocation after the @. 470.It Dq recorded old size oldsize != size 471.Fn recallocarray 472has detected that the given old size does not equal the recorded size in its 473meta data. 474Enabling option 475.Cm C 476allows 477.Fn recallocarray 478to catch more of these cases. 479.It Dq recursive call 480An attempt was made to call recursively into these functions, i.e., from a 481signal handler. 482This behavior is not supported. 483In particular, signal handlers should 484.Em not 485use any of the 486.Fn malloc 487functions nor utilize any other functions which may call 488.Fn malloc 489(e.g., 490.Xr stdio 3 491routines). 492.It Dq unknown char in MALLOC_OPTIONS 493We found something we didn't understand. 494.It any other error 495.Fn malloc 496detected an internal error; 497consult sources and/or wizards. 498.El 499.Sh SEE ALSO 500.Xr brk 2 , 501.Xr mmap 2 , 502.Xr munmap 2 , 503.Xr alloca 3 , 504.Xr getpagesize 3 , 505.Xr posix_memalign 3 , 506.Xr sysconf 3 , 507.Xr malloc.conf 5 508.Sh STANDARDS 509The 510.Fn malloc , 511.Fn calloc , 512.Fn realloc , 513and 514.Fn free 515functions conform to 516.St -ansiC . 517.Pp 518If 519.Fa nmemb 520or 521.Fa size 522are 0, the return value is implementation defined; 523other conforming implementations may return 524.Dv NULL 525in this case. 526.Pp 527The 528.Ev MALLOC_OPTIONS 529environment variable, the file 530.Pa /etc/malloc.conf , 531and the 532.Sx DIAGNOSTICS 533output are extensions to the standard. 534.Sh HISTORY 535A 536.Fn free 537internal kernel function and a predecessor to 538.Fn malloc , 539.Fn alloc , 540first appeared in 541.At v1 . 542C library functions 543.Fn alloc 544and 545.Fn free 546appeared in 547.At v6 . 548The functions 549.Fn malloc , 550.Fn calloc , 551and 552.Fn realloc 553first appeared in 554.At v7 . 555.Pp 556A new implementation by Chris Kingsley was introduced in 557.Bx 4.2 , 558followed by a complete rewrite by Poul-Henning Kamp which appeared in 559.Fx 2.2 560and was included in 561.Ox 2.0 . 562These implementations were all 563.Xr sbrk 2 564based. 565In 566.Ox 3.8 , 567Thierry Deval rewrote 568.Nm 569to use the 570.Xr mmap 2 571system call, 572making the page addresses returned by 573.Nm 574random. 575A rewrite by Otto Moerbeek introducing a new central data structure and more 576randomization appeared in 577.Ox 4.4 . 578.Pp 579The 580.Fn reallocarray 581function appeared in 582.Ox 5.6 . 583The 584.Fn recallocarray 585function appeared in 586.Ox 6.1 . 587The 588.Fn freezero 589function appeared in 590.Ox 6.2 . 591.Sh CAVEATS 592When using 593.Fn malloc , 594be wary of signed integer and 595.Vt size_t 596overflow especially when there is multiplication in the 597.Fa size 598argument. 599.Pp 600Signed integer overflow will cause undefined behavior which compilers 601typically handle by wrapping back around to negative numbers. 602Depending on the input, this can result in allocating more or less 603memory than intended. 604.Pp 605An unsigned overflow has defined behavior which will wrap back around and 606return less memory than intended. 607.Pp 608A signed or unsigned integer overflow is a 609.Em security 610risk if less memory is returned than intended. 611Subsequent code may corrupt the heap by writing beyond the memory that was 612allocated. 613An attacker may be able to leverage this heap corruption to execute arbitrary 614code. 615.Pp 616Consider using 617.Fn calloc , 618.Fn reallocarray 619or 620.Fn recallocarray 621instead of using multiplication in 622.Fn malloc 623and 624.Fn realloc 625to avoid these problems on 626.Ox . 627