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