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.126 2019/09/14 13:16:50 otto Exp $ 34.\" 35.Dd $Mdocdate: September 14 2019 $ 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 statistics to the file 288.Pa ./malloc.out , 289if it already exists, 290at exit. 291This option requires the library to have been compiled with -DMALLOC_STATS in 292order to have any effect. 293.It Cm F 294.Dq Freecheck . 295Enable more extensive double free and use after free detection. 296All chunks in the delayed free list will be checked for double frees. 297Unused pages on the freelist are read and write protected to 298cause a segmentation fault upon access. 299.It Cm G 300.Dq Guard . 301Enable guard pages. 302Each page size or larger allocation is followed by a guard page that will 303cause a segmentation fault upon any access. 304.It Cm J 305.Dq More junking . 306Increase the junk level by one if it is smaller than 2. 307.It Cm j 308.Dq Less junking . 309Decrease the junk level by one if it is larger than 0. 310Junking writes some junk bytes into the area allocated. 311Junk is bytes of 0xdb when allocating; 312freed chunks are filled with 0xdf. 313By default the junk level is 1: after free, 314small chunks are completely junked; 315for pages the first part is junked. 316After a delay, 317the filling pattern is validated and the process is aborted if the pattern 318was modified. 319For junk level 2, junking is done on allocation as well and without size 320restrictions. 321If the junk level is zero, no junking is performed. 322.It Cm R 323.Dq realloc . 324Always reallocate when 325.Fn realloc 326is called, even if the initial allocation was big enough. 327.\".Pp 328.\".It Cm U 329.\".Dq utrace . 330.\"Generate entries for 331.\".Xr ktrace 1 332.\"for all operations. 333.\"Consult the source for this one. 334.It Cm S 335.\" Malloc option S is vaguely documented on purpose. 336Enable all options suitable for security auditing. 337.It Cm U 338.Dq Free unmap . 339Enable use after free protection for larger allocations. 340Unused pages on the freelist are read and write protected to 341cause a segmentation fault upon access. 342.It Cm X 343.Dq xmalloc . 344Rather than return failure, 345.Xr abort 3 346the program with a diagnostic message on stderr. 347It is the intention that this option be set at compile time by 348including in the source: 349.Bd -literal -offset indent 350extern char *malloc_options; 351malloc_options = "X"; 352.Ed 353.Pp 354Note that this will cause code that is supposed to handle 355out-of-memory conditions gracefully to abort instead. 356.It Cm < 357.Dq Halve the cache size . 358Decrease the size of the free page cache by a factor of two. 359.It Cm > 360.Dq Double the cache size . 361Increase the size of the free page cache by a factor of two. 362.El 363.Pp 364If a program changes behavior if any of these options (except 365.Cm X ) 366are used, 367it is buggy. 368.Pp 369The default number of free pages cached is 64 per malloc pool. 370Multi-threaded programs use multiple pools. 371.Sh RETURN VALUES 372Upon successful completion, the allocation functions 373return a pointer to the allocated space; otherwise, 374.Dv NULL 375is returned and 376.Va errno 377is set to 378.Er ENOMEM . 379The function 380.Fn aligned_alloc 381returns 382.Dv NULL 383and sets 384.Va errno 385to 386.Er EINVAL 387if 388.Fa alignment 389is not a power of 2. 390.Pp 391If 392.Fa nmemb 393or 394.Fa size 395is equal to 0, a unique pointer to an access protected, 396zero sized object is returned. 397Access via this pointer will generate a 398.Dv SIGSEGV 399exception. 400.Pp 401If multiplying 402.Fa nmemb 403and 404.Fa size 405results in integer overflow, 406.Fn calloc , 407.Fn reallocarray 408and 409.Fn recallocarray 410return 411.Dv NULL 412and set 413.Va errno 414to 415.Er ENOMEM . 416.Pp 417If 418.Fa ptr 419is not 420.Dv NULL 421and multiplying 422.Fa oldnmemb 423and 424.Fa size 425results in integer overflow 426.Fn recallocarray 427returns 428.Dv NULL 429and sets 430.Va errno 431to 432.Er EINVAL . 433.Sh IDIOMS 434Consider 435.Fn calloc 436or the extensions 437.Fn reallocarray 438and 439.Fn recallocarray 440when there is multiplication in the 441.Fa size 442argument of 443.Fn malloc 444or 445.Fn realloc . 446For example, avoid this common idiom as it may lead to integer overflow: 447.Bd -literal -offset indent 448if ((p = malloc(num * size)) == NULL) 449 err(1, NULL); 450.Ed 451.Pp 452A drop-in replacement is the 453.Ox 454extension 455.Fn reallocarray : 456.Bd -literal -offset indent 457if ((p = reallocarray(NULL, num, size)) == NULL) 458 err(1, NULL); 459.Ed 460.Pp 461Alternatively, 462.Fn calloc 463may be used at the cost of initialization overhead. 464.Pp 465When using 466.Fn realloc , 467be careful to avoid the following idiom: 468.Bd -literal -offset indent 469size += 50; 470if ((p = realloc(p, size)) == NULL) 471 return (NULL); 472.Ed 473.Pp 474Do not adjust the variable describing how much memory has been allocated 475until the allocation has been successful. 476This can cause aberrant program behavior if the incorrect size value is used. 477In most cases, the above sample will also result in a leak of memory. 478As stated earlier, a return value of 479.Dv NULL 480indicates that the old object still remains allocated. 481Better code looks like this: 482.Bd -literal -offset indent 483newsize = size + 50; 484if ((newp = realloc(p, newsize)) == NULL) { 485 free(p); 486 p = NULL; 487 size = 0; 488 return (NULL); 489} 490p = newp; 491size = newsize; 492.Ed 493.Pp 494As with 495.Fn malloc , 496it is important to ensure the new size value will not overflow; 497i.e. avoid allocations like the following: 498.Bd -literal -offset indent 499if ((newp = realloc(p, num * size)) == NULL) { 500 ... 501.Ed 502.Pp 503Instead, use 504.Fn reallocarray : 505.Bd -literal -offset indent 506if ((newp = reallocarray(p, num, size)) == NULL) { 507 ... 508.Ed 509.Pp 510Calling 511.Fn realloc 512with a 513.Dv NULL 514.Fa ptr 515is equivalent to calling 516.Fn malloc . 517Instead of this idiom: 518.Bd -literal -offset indent 519if (p == NULL) 520 newp = malloc(newsize); 521else 522 newp = realloc(p, newsize); 523.Ed 524.Pp 525Use the following: 526.Bd -literal -offset indent 527newp = realloc(p, newsize); 528.Ed 529.Pp 530The 531.Fn recallocarray 532function should be used for resizing objects containing sensitive data like 533keys. 534To avoid leaking information, 535it guarantees memory is cleared before placing it on the internal free list. 536Deallocation of such an object should be done by calling 537.Fn freezero . 538.Sh ENVIRONMENT 539.Bl -tag -width "MALLOC_OPTIONS" 540.It Ev MALLOC_OPTIONS 541String of option flags. 542.El 543.Sh EXAMPLES 544If 545.Fn malloc 546must be used with multiplication, be sure to test for overflow: 547.Bd -literal -offset indent 548size_t num, size; 549\&... 550 551/* Check for size_t overflow */ 552if (size && num > SIZE_MAX / size) 553 errc(1, EOVERFLOW, "overflow"); 554 555if ((p = malloc(num * size)) == NULL) 556 err(1, NULL); 557.Ed 558.Pp 559The above test is not sufficient in all cases. 560For example, multiplying ints requires a different set of checks: 561.Bd -literal -offset indent 562int num, size; 563\&... 564 565/* Avoid invalid requests */ 566if (size < 0 || num < 0) 567 errc(1, EOVERFLOW, "overflow"); 568 569/* Check for signed int overflow */ 570if (size && num > INT_MAX / size) 571 errc(1, EOVERFLOW, "overflow"); 572 573if ((p = malloc(num * size)) == NULL) 574 err(1, NULL); 575.Ed 576.Pp 577Assuming the implementation checks for integer overflow as 578.Ox 579does, it is much easier to use 580.Fn calloc , 581.Fn reallocarray , 582or 583.Fn recallocarray . 584.Pp 585The above examples could be simplified to: 586.Bd -literal -offset indent 587if ((p = reallocarray(NULL, num, size)) == NULL) 588 err(1, NULL); 589.Ed 590.Pp 591or at the cost of initialization: 592.Bd -literal -offset indent 593if ((p = calloc(num, size)) == NULL) 594 err(1, NULL); 595.Ed 596.Pp 597Set a systemwide reduction of the cache to a quarter of the 598default size and use guard pages: 599.Pp 600.Dl # sysctl vm.malloc_conf='G<<' 601.Sh DIAGNOSTICS 602If any of the functions detect an error condition, 603a message will be printed to file descriptor 6042 (not using stdio). 605Errors will result in the process being aborted. 606.Pp 607Here is a brief description of the error messages and what they mean: 608.Bl -tag -width Ds 609.It Dq out of memory 610If the 611.Cm X 612option is specified it is an error for the allocation functions 613to return 614.Dv NULL . 615.It Dq bogus pointer (double free?) 616An attempt to 617.Fn free 618or 619reallocate an unallocated pointer was made. 620.It Dq chunk is already free 621There was an attempt to free a chunk that had already been freed. 622.It Dq use after free 623A chunk has been modified after it was freed. 624.It Dq modified chunk-pointer 625The pointer passed to 626.Fn free 627or a reallocation function has been modified. 628.It Dq chunk canary corrupted address offset@length 629A byte after the requested size has been overwritten, 630indicating a heap overflow. 631The offset at which corruption was detected is printed before the @, 632and the requested length of the allocation after the @. 633.It Dq recorded old size oldsize != size 634.Fn recallocarray 635has detected that the given old size does not equal the recorded size in its 636meta data. 637Enabling option 638.Cm C 639allows 640.Fn recallocarray 641to catch more of these cases. 642.It Dq recursive call 643An attempt was made to call recursively into these functions, i.e., from a 644signal handler. 645This behavior is not supported. 646In particular, signal handlers should 647.Em not 648use any of the 649.Fn malloc 650functions nor utilize any other functions which may call 651.Fn malloc 652(e.g., 653.Xr stdio 3 654routines). 655.It Dq unknown char in MALLOC_OPTIONS 656We found something we didn't understand. 657.It any other error 658.Fn malloc 659detected an internal error; 660consult sources and/or wizards. 661.El 662.Sh SEE ALSO 663.Xr brk 2 , 664.Xr mmap 2 , 665.Xr munmap 2 , 666.Xr sysctl 2 , 667.Xr alloca 3 , 668.Xr getpagesize 3 , 669.Xr posix_memalign 3 670.Sh STANDARDS 671The 672.Fn malloc , 673.Fn calloc , 674.Fn realloc , 675and 676.Fn free 677functions conform to 678.St -ansiC . 679The 680.Fn aligned_alloc 681function conforms to 682.St -isoC-2011 . 683.Pp 684If 685.Fa nmemb 686or 687.Fa size 688are 0, the return value is implementation defined; 689other conforming implementations may return 690.Dv NULL 691in this case. 692.Pp 693The 694.Ev MALLOC_OPTIONS 695environment variable, the 696.Va vm.malloc_conf 697sysctl and the 698.Sx DIAGNOSTICS 699output are extensions to the standard. 700.Sh HISTORY 701A 702.Fn free 703internal kernel function and a predecessor to 704.Fn malloc , 705.Fn alloc , 706first appeared in 707.At v1 . 708C library functions 709.Fn alloc 710and 711.Fn free 712appeared in 713.At v6 . 714The functions 715.Fn malloc , 716.Fn calloc , 717and 718.Fn realloc 719first appeared in 720.At v7 . 721.Pp 722A new implementation by Chris Kingsley was introduced in 723.Bx 4.2 , 724followed by a complete rewrite by Poul-Henning Kamp which appeared in 725.Fx 2.2 726and was included in 727.Ox 2.0 . 728These implementations were all 729.Xr sbrk 2 730based. 731In 732.Ox 3.8 , 733Thierry Deval rewrote 734.Nm 735to use the 736.Xr mmap 2 737system call, 738making the page addresses returned by 739.Nm 740random. 741A rewrite by Otto Moerbeek introducing a new central data structure and more 742randomization appeared in 743.Ox 4.4 . 744.Pp 745The 746.Fn reallocarray 747function appeared in 748.Ox 5.6 . 749The 750.Fn recallocarray 751function appeared in 752.Ox 6.1 . 753The 754.Fn freezero 755function appeared in 756.Ox 6.2 . 757The 758.Fn aligned_alloc 759function appeared in 760.Ox 6.5 . 761The 762.Fn malloc_conceal 763and 764.Fn calloc_conceal 765functions appeared in 766.Ox 6.6 . 767.Sh CAVEATS 768When using 769.Fn malloc , 770be wary of signed integer and 771.Vt size_t 772overflow especially when there is multiplication in the 773.Fa size 774argument. 775.Pp 776Signed integer overflow will cause undefined behavior which compilers 777typically handle by wrapping back around to negative numbers. 778Depending on the input, this can result in allocating more or less 779memory than intended. 780.Pp 781An unsigned overflow has defined behavior which will wrap back around and 782return less memory than intended. 783.Pp 784A signed or unsigned integer overflow is a 785.Em security 786risk if less memory is returned than intended. 787Subsequent code may corrupt the heap by writing beyond the memory that was 788allocated. 789An attacker may be able to leverage this heap corruption to execute arbitrary 790code. 791.Pp 792Consider using 793.Fn calloc , 794.Fn reallocarray 795or 796.Fn recallocarray 797instead of using multiplication in 798.Fn malloc 799and 800.Fn realloc 801to avoid these problems on 802.Ox . 803