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