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.121 2018/11/21 09:22:58 jmc Exp $ 34.\" 35.Dd $Mdocdate: November 21 2018 $ 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.Nm aligned_alloc 47.Nd memory allocation and deallocation 48.Sh SYNOPSIS 49.In stdlib.h 50.Ft void * 51.Fn malloc "size_t size" 52.Ft void * 53.Fn calloc "size_t nmemb" "size_t size" 54.Ft void * 55.Fn realloc "void *ptr" "size_t size" 56.Ft void 57.Fn free "void *ptr" 58.Ft void * 59.Fn reallocarray "void *ptr" "size_t nmemb" "size_t size" 60.Ft void * 61.Fn recallocarray "void *ptr" "size_t oldnmemb" "size_t nmemb" "size_t size" 62.Ft void 63.Fn freezero "void *ptr" "size_t size" 64.Ft void * 65.Fn aligned_alloc "size_t alignment" "size_t size" 66.Ft size_t 67.Vt char *malloc_options ; 68.Sh DESCRIPTION 69The standard functions 70.Fn malloc , 71.Fn calloc , 72and 73.Fn realloc 74allocate 75.Em objects , 76regions of memory to store values. 77The 78.Fn malloc 79function allocates uninitialized space for an object of 80the specified 81.Fa size . 82.Fn malloc 83maintains multiple lists of free objects according to size, allocating 84from the appropriate list or requesting memory from the kernel. 85The allocated space is suitably aligned (after possible pointer coercion) for 86storage of any type of object. 87.Pp 88The 89.Fn calloc 90function allocates space for an array of 91.Fa nmemb 92objects, each of the specified 93.Fa size . 94The space is initialized to zero. 95.Pp 96The 97.Fn realloc 98function changes the size of the object pointed to by 99.Fa ptr 100to 101.Fa size 102bytes and returns a pointer to the (possibly moved) object. 103If 104.Fa ptr 105is not 106.Dv NULL , 107it must be a pointer returned by an earlier call to an allocation or 108reallocation function that was not freed in between. 109The contents of the object are unchanged up to the lesser 110of the new and old sizes. 111If the new size is larger, the value of the newly allocated portion 112of the object is indeterminate and uninitialized. 113If the space cannot be allocated, the object 114pointed to by 115.Fa ptr 116is unchanged. 117If 118.Fa ptr 119is 120.Dv NULL , 121.Fn realloc 122behaves like 123.Fn malloc 124and allocates a new object. 125.Pp 126The 127.Fn free 128function causes the space pointed to by 129.Fa ptr 130to be either placed on a list of free blocks to make it available for future 131allocation or, when appropriate, to be returned to the kernel using 132.Xr munmap 2 . 133If 134.Fa ptr 135is 136.Dv NULL , 137no action occurs. 138If 139.Fa ptr 140was previously freed by 141.Fn free 142or a reallocation function, 143the behavior is undefined and the double free is a security concern. 144.Pp 145Designed for safe allocation of arrays, 146the 147.Fn reallocarray 148function is similar to 149.Fn realloc 150except it operates on 151.Fa nmemb 152members of size 153.Fa size 154and checks for integer overflow in the calculation 155.Fa nmemb 156* 157.Fa size . 158.Pp 159Used for the allocation of memory holding sensitive data, 160the 161.Fn recallocarray 162and 163.Fn freezero 164functions guarantee that memory becoming unallocated is explicitly 165.Em discarded , 166meaning pages of memory are disposed via 167.Xr munmap 2 168and cached free objects are cleared with 169.Xr explicit_bzero 3 . 170.Pp 171The 172.Fn recallocarray 173function is similar to 174.Fn reallocarray 175except it ensures newly allocated memory is cleared similar to 176.Fn calloc . 177If 178.Fa ptr 179is 180.Dv NULL , 181.Fa oldnmemb 182is ignored and the call is equivalent to 183.Fn calloc . 184If 185.Fa ptr 186is not 187.Dv NULL , 188.Fa oldnmemb 189must be a value such that 190.Fa oldnmemb 191* 192.Fa size 193is the size of the earlier allocation that returned 194.Fa ptr , 195otherwise the behavior is undefined. 196.Pp 197The 198.Fn freezero 199function is similar to the 200.Fn free 201function except it ensures memory is explicitly discarded. 202If 203.Fa ptr 204is 205.Dv NULL , 206no action occurs. 207If 208.Fa ptr 209is not 210.Dv NULL , 211the 212.Fa size 213argument must be equal to or smaller than the size of the earlier allocation 214that returned 215.Fa ptr . 216.Fn freezero 217guarantees the memory range starting at 218.Fa ptr 219with length 220.Fa size 221is discarded while deallocating the whole object originally allocated. 222.Pp 223The 224.Fn aligned_alloc 225function allocates 226.Fa size 227bytes of memory such that the allocation's base address is a multiple of 228.Fa alignment . 229The requested 230.Fa alignment 231must be a power of 2. 232If 233.Fa size 234is not a multiple of 235.Fa alignment , 236behavior is undefined. 237.Sh MALLOC OPTIONS 238Upon the first call to the 239.Fn malloc 240family of functions, an initialization sequence inspects the 241value of the 242.Va vm.malloc_conf 243.Xr sysctl 2 , 244next checks the environment for a variable called 245.Ev MALLOC_OPTIONS , 246and finally looks at the global variable 247.Va malloc_options 248in the program. 249Each is scanned for the flags documented below. 250Unless otherwise noted uppercase means on, lowercase means off. 251.Bl -tag -width indent 252.It Cm C 253.Dq Canaries . 254Add canaries at the end of allocations in order to detect 255heap overflows. 256The canary's content is checked when 257.Nm free 258is called. 259If it has been corrupted, the process is aborted. 260.It Cm D 261.Dq Dump . 262.Fn malloc 263will dump statistics to the file 264.Pa ./malloc.out , 265if it already exists, 266at exit. 267This option requires the library to have been compiled with -DMALLOC_STATS in 268order to have any effect. 269.It Cm F 270.Dq Freecheck . 271Enable more extensive double free and use after free detection. 272All chunks in the delayed free list will be checked for double frees. 273Unused pages on the freelist are read and write protected to 274cause a segmentation fault upon access. 275.It Cm G 276.Dq Guard . 277Enable guard pages. 278Each page size or larger allocation is followed by a guard page that will 279cause a segmentation fault upon any access. 280.It Cm J 281.Dq More junking . 282Increase the junk level by one if it is smaller than 2. 283.It Cm j 284.Dq Less junking . 285Decrease the junk level by one if it is larger than 0. 286Junking writes some junk bytes into the area allocated. 287Junk is bytes of 0xdb when allocating; 288freed chunks are filled with 0xdf. 289By default the junk level is 1: after free, 290small chunks are completely junked; 291for pages the first part is junked. 292After a delay, 293the filling pattern is validated and the process is aborted if the pattern 294was modified. 295For junk level 2, junking is done on allocation as well and without size 296restrictions. 297If the junk level is zero, no junking is performed. 298.It Cm R 299.Dq realloc . 300Always reallocate when 301.Fn realloc 302is called, even if the initial allocation was big enough. 303.\".Pp 304.\".It Cm U 305.\".Dq utrace . 306.\"Generate entries for 307.\".Xr ktrace 1 308.\"for all operations. 309.\"Consult the source for this one. 310.It Cm S 311Enable all options suitable for security auditing. 312.It Cm U 313.Dq Free unmap . 314Enable use after free protection for larger allocations. 315Unused pages on the freelist are read and write protected to 316cause a segmentation fault upon access. 317.It Cm X 318.Dq xmalloc . 319Rather than return failure, 320.Xr abort 3 321the program with a diagnostic message on stderr. 322It is the intention that this option be set at compile time by 323including in the source: 324.Bd -literal -offset indent 325extern char *malloc_options; 326malloc_options = "X"; 327.Ed 328.Pp 329Note that this will cause code that is supposed to handle 330out-of-memory conditions gracefully to abort instead. 331.It Cm < 332.Dq Halve the cache size . 333Decrease the size of the free page cache by a factor of two. 334.It Cm > 335.Dq Double the cache size . 336Increase the size of the free page cache by a factor of two. 337.El 338.Pp 339If a program changes behavior if any of these options (except 340.Cm X ) 341are used, 342it is buggy. 343.Pp 344The default number of free pages cached is 64 per malloc pool. 345Multi-threaded programs use multiple pools. 346.Sh RETURN VALUES 347Upon successful completion, the allocation functions 348return a pointer to the allocated space; otherwise, 349.Dv NULL 350is returned and 351.Va errno 352is set to 353.Er ENOMEM . 354The function 355.Fn aligned_alloc 356returns 357.Dv NULL 358and sets 359.Va errno 360to 361.Er EINVAL 362if 363.Fa alignment 364is not a power of 2. 365.Pp 366If 367.Fa nmemb 368or 369.Fa size 370is equal to 0, a unique pointer to an access protected, 371zero sized object is returned. 372Access via this pointer will generate a 373.Dv SIGSEGV 374exception. 375.Pp 376If multiplying 377.Fa nmemb 378and 379.Fa size 380results in integer overflow, 381.Fn calloc , 382.Fn reallocarray 383and 384.Fn recallocarray 385return 386.Dv NULL 387and set 388.Va errno 389to 390.Er ENOMEM . 391.Pp 392If 393.Fa ptr 394is not 395.Dv NULL 396and multiplying 397.Fa oldnmemb 398and 399.Fa size 400results in integer overflow 401.Fn recallocarray 402returns 403.Dv NULL 404and sets 405.Va errno 406to 407.Er EINVAL . 408.Sh IDIOMS 409Consider 410.Fn calloc 411or the extensions 412.Fn reallocarray 413and 414.Fn recallocarray 415when there is multiplication in the 416.Fa size 417argument of 418.Fn malloc 419or 420.Fn realloc . 421For example, avoid this common idiom as it may lead to integer overflow: 422.Bd -literal -offset indent 423if ((p = malloc(num * size)) == NULL) 424 err(1, NULL); 425.Ed 426.Pp 427A drop-in replacement is the 428.Ox 429extension 430.Fn reallocarray : 431.Bd -literal -offset indent 432if ((p = reallocarray(NULL, num, size)) == NULL) 433 err(1, NULL); 434.Ed 435.Pp 436Alternatively, 437.Fn calloc 438may be used at the cost of initialization overhead. 439.Pp 440When using 441.Fn realloc , 442be careful to avoid the following idiom: 443.Bd -literal -offset indent 444size += 50; 445if ((p = realloc(p, size)) == NULL) 446 return (NULL); 447.Ed 448.Pp 449Do not adjust the variable describing how much memory has been allocated 450until the allocation has been successful. 451This can cause aberrant program behavior if the incorrect size value is used. 452In most cases, the above sample will also result in a leak of memory. 453As stated earlier, a return value of 454.Dv NULL 455indicates that the old object still remains allocated. 456Better code looks like this: 457.Bd -literal -offset indent 458newsize = size + 50; 459if ((newp = realloc(p, newsize)) == NULL) { 460 free(p); 461 p = NULL; 462 size = 0; 463 return (NULL); 464} 465p = newp; 466size = newsize; 467.Ed 468.Pp 469As with 470.Fn malloc , 471it is important to ensure the new size value will not overflow; 472i.e. avoid allocations like the following: 473.Bd -literal -offset indent 474if ((newp = realloc(p, num * size)) == NULL) { 475 ... 476.Ed 477.Pp 478Instead, use 479.Fn reallocarray : 480.Bd -literal -offset indent 481if ((newp = reallocarray(p, num, size)) == NULL) { 482 ... 483.Ed 484.Pp 485Calling 486.Fn realloc 487with a 488.Dv NULL 489.Fa ptr 490is equivalent to calling 491.Fn malloc . 492Instead of this idiom: 493.Bd -literal -offset indent 494if (p == NULL) 495 newp = malloc(newsize); 496else 497 newp = realloc(p, newsize); 498.Ed 499.Pp 500Use the following: 501.Bd -literal -offset indent 502newp = realloc(p, newsize); 503.Ed 504.Pp 505The 506.Fn recallocarray 507function should be used for resizing objects containing sensitive data like 508keys. 509To avoid leaking information, 510it guarantees memory is cleared before placing it on the internal free list. 511Deallocation of such an object should be done by calling 512.Fn freezero . 513.Sh ENVIRONMENT 514.Bl -tag -width "MALLOC_OPTIONS" 515.It Ev MALLOC_OPTIONS 516String of option flags. 517.El 518.Sh EXAMPLES 519If 520.Fn malloc 521must be used with multiplication, be sure to test for overflow: 522.Bd -literal -offset indent 523size_t num, size; 524\&... 525 526/* Check for size_t overflow */ 527if (size && num > SIZE_MAX / size) 528 errc(1, EOVERFLOW, "overflow"); 529 530if ((p = malloc(num * size)) == NULL) 531 err(1, NULL); 532.Ed 533.Pp 534The above test is not sufficient in all cases. 535For example, multiplying ints requires a different set of checks: 536.Bd -literal -offset indent 537int num, size; 538\&... 539 540/* Avoid invalid requests */ 541if (size < 0 || num < 0) 542 errc(1, EOVERFLOW, "overflow"); 543 544/* Check for signed int overflow */ 545if (size && num > INT_MAX / size) 546 errc(1, EOVERFLOW, "overflow"); 547 548if ((p = malloc(num * size)) == NULL) 549 err(1, NULL); 550.Ed 551.Pp 552Assuming the implementation checks for integer overflow as 553.Ox 554does, it is much easier to use 555.Fn calloc , 556.Fn reallocarray , 557or 558.Fn recallocarray . 559.Pp 560The above examples could be simplified to: 561.Bd -literal -offset indent 562if ((p = reallocarray(NULL, num, size)) == NULL) 563 err(1, NULL); 564.Ed 565.Pp 566or at the cost of initialization: 567.Bd -literal -offset indent 568if ((p = calloc(num, size)) == NULL) 569 err(1, NULL); 570.Ed 571.Pp 572Set a systemwide reduction of the cache to a quarter of the 573default size and use guard pages: 574.Pp 575.Dl # sysctl vm.malloc_conf='G<<' 576.Sh DIAGNOSTICS 577If any of the functions detect an error condition, 578a message will be printed to file descriptor 5792 (not using stdio). 580Errors will result in the process being aborted. 581.Pp 582Here is a brief description of the error messages and what they mean: 583.Bl -tag -width Ds 584.It Dq out of memory 585If the 586.Cm X 587option is specified it is an error for the allocation functions 588to return 589.Dv NULL . 590.It Dq bogus pointer (double free?) 591An attempt to 592.Fn free 593or 594reallocate an unallocated pointer was made. 595.It Dq chunk is already free 596There was an attempt to free a chunk that had already been freed. 597.It Dq use after free 598A chunk has been modified after it was freed. 599.It Dq modified chunk-pointer 600The pointer passed to 601.Fn free 602or a reallocation function has been modified. 603.It Dq chunk canary corrupted address offset@length 604A byte after the requested size has been overwritten, 605indicating a heap overflow. 606The offset at which corruption was detected is printed before the @, 607and the requested length of the allocation after the @. 608.It Dq recorded old size oldsize != size 609.Fn recallocarray 610has detected that the given old size does not equal the recorded size in its 611meta data. 612Enabling option 613.Cm C 614allows 615.Fn recallocarray 616to catch more of these cases. 617.It Dq recursive call 618An attempt was made to call recursively into these functions, i.e., from a 619signal handler. 620This behavior is not supported. 621In particular, signal handlers should 622.Em not 623use any of the 624.Fn malloc 625functions nor utilize any other functions which may call 626.Fn malloc 627(e.g., 628.Xr stdio 3 629routines). 630.It Dq unknown char in MALLOC_OPTIONS 631We found something we didn't understand. 632.It any other error 633.Fn malloc 634detected an internal error; 635consult sources and/or wizards. 636.El 637.Sh SEE ALSO 638.Xr brk 2 , 639.Xr mmap 2 , 640.Xr munmap 2 , 641.Xr sysctl 2 , 642.Xr alloca 3 , 643.Xr getpagesize 3 , 644.Xr posix_memalign 3 645.Sh STANDARDS 646The 647.Fn malloc , 648.Fn calloc , 649.Fn realloc , 650and 651.Fn free 652functions conform to 653.St -ansiC . 654The 655.Fn aligned_alloc 656function conforms to 657.St -isoC-2011 . 658.Pp 659If 660.Fa nmemb 661or 662.Fa size 663are 0, the return value is implementation defined; 664other conforming implementations may return 665.Dv NULL 666in this case. 667.Pp 668The 669.Ev MALLOC_OPTIONS 670environment variable, the 671.Va vm.malloc_conf 672sysctl and the 673.Sx DIAGNOSTICS 674output are extensions to the standard. 675.Sh HISTORY 676A 677.Fn free 678internal kernel function and a predecessor to 679.Fn malloc , 680.Fn alloc , 681first appeared in 682.At v1 . 683C library functions 684.Fn alloc 685and 686.Fn free 687appeared in 688.At v6 . 689The functions 690.Fn malloc , 691.Fn calloc , 692and 693.Fn realloc 694first appeared in 695.At v7 . 696.Pp 697A new implementation by Chris Kingsley was introduced in 698.Bx 4.2 , 699followed by a complete rewrite by Poul-Henning Kamp which appeared in 700.Fx 2.2 701and was included in 702.Ox 2.0 . 703These implementations were all 704.Xr sbrk 2 705based. 706In 707.Ox 3.8 , 708Thierry Deval rewrote 709.Nm 710to use the 711.Xr mmap 2 712system call, 713making the page addresses returned by 714.Nm 715random. 716A rewrite by Otto Moerbeek introducing a new central data structure and more 717randomization appeared in 718.Ox 4.4 . 719.Pp 720The 721.Fn reallocarray 722function appeared in 723.Ox 5.6 . 724The 725.Fn recallocarray 726function appeared in 727.Ox 6.1 . 728The 729.Fn freezero 730function appeared in 731.Ox 6.2 . 732The 733.Fn aligned_alloc 734function appeared in 735.Ox 6.5 . 736.Sh CAVEATS 737When using 738.Fn malloc , 739be wary of signed integer and 740.Vt size_t 741overflow especially when there is multiplication in the 742.Fa size 743argument. 744.Pp 745Signed integer overflow will cause undefined behavior which compilers 746typically handle by wrapping back around to negative numbers. 747Depending on the input, this can result in allocating more or less 748memory than intended. 749.Pp 750An unsigned overflow has defined behavior which will wrap back around and 751return less memory than intended. 752.Pp 753A signed or unsigned integer overflow is a 754.Em security 755risk if less memory is returned than intended. 756Subsequent code may corrupt the heap by writing beyond the memory that was 757allocated. 758An attacker may be able to leverage this heap corruption to execute arbitrary 759code. 760.Pp 761Consider using 762.Fn calloc , 763.Fn reallocarray 764or 765.Fn recallocarray 766instead of using multiplication in 767.Fn malloc 768and 769.Fn realloc 770to avoid these problems on 771.Ox . 772