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.71 2012/11/02 18:18:15 djm Exp $ 34.\" 35.Dd $Mdocdate: November 2 2012 $ 36.Dt MALLOC 3 37.Os 38.Sh NAME 39.Nm malloc , 40.Nm calloc , 41.Nm realloc , 42.Nm free , 43.Nm cfree 44.Nd memory allocation and deallocation 45.Sh SYNOPSIS 46.Fd #include <stdlib.h> 47.Ft void * 48.Fn malloc "size_t size" 49.Ft void * 50.Fn calloc "size_t nmemb" "size_t size" 51.Ft void * 52.Fn realloc "void *ptr" "size_t size" 53.Ft void 54.Fn free "void *ptr" 55.Ft void 56.Fn cfree "void *ptr" 57.Ft char * 58.Va malloc_options ; 59.Sh DESCRIPTION 60The 61.Fn malloc 62function allocates uninitialized space for an object whose 63size is specified by 64.Fa size . 65The 66.Fn malloc 67function maintains multiple lists of free blocks according to size, allocating 68space from the appropriate list. 69.Pp 70The allocated space is 71suitably aligned (after possible pointer 72coercion) for storage of any type of object. 73If the space is of 74.Em pagesize 75or larger, the memory returned will be page-aligned. 76.Pp 77Allocation of a zero size object returns a pointer to a zero size object. 78This zero size object is access protected, so any access to it will 79generate an exception (SIGSEGV). 80Many zero-sized objects can be placed consecutively in shared 81protected pages. 82The minimum size of the protection on each object is suitably aligned and 83sized as previously stated, but the protection may extend further depending 84on where in a protected zone the object lands. 85.Pp 86When using 87.Fn malloc 88be careful to avoid the following idiom: 89.Bd -literal -offset indent 90if ((p = malloc(num * size)) == NULL) 91 err(1, "malloc"); 92.Ed 93.Pp 94The multiplication may lead to an integer overflow. 95To avoid this, 96.Fn calloc 97is recommended. 98.Pp 99If 100.Fn malloc 101must be used, be sure to test for overflow: 102.Bd -literal -offset indent 103if (size && num > SIZE_MAX / size) { 104 errno = ENOMEM; 105 err(1, "overflow"); 106} 107.Ed 108.Pp 109The 110.Fn calloc 111function allocates space for an array of 112.Fa nmemb 113objects, each of whose size is 114.Fa size . 115The space is initialized to zero. 116The use of 117.Fn calloc 118is strongly encouraged when allocating multiple sized objects 119in order to avoid possible integer overflows. 120.Pp 121The 122.Fn free 123function causes the space pointed to by 124.Fa ptr 125to be either placed on a list of free pages to make it available for future 126allocation or, if required, to be returned to the kernel using 127.Xr munmap 2 . 128If 129.Fa ptr 130is a null pointer, no action occurs. 131.Pp 132A 133.Fn cfree 134function is also provided for compatibility with old systems and other 135.Nm malloc 136libraries; it is simply an alias for 137.Fn free . 138.Pp 139The 140.Fn realloc 141function changes the size of the object pointed to by 142.Fa ptr 143to 144.Fa size 145bytes and returns a pointer to the (possibly moved) object. 146The contents of the object are unchanged up to the lesser 147of the new and old sizes. 148If the new size is larger, the value of the newly allocated portion 149of the object is indeterminate and uninitialized. 150If 151.Fa ptr 152is a null pointer, the 153.Fn realloc 154function behaves like the 155.Fn malloc 156function for the specified size. 157If the space cannot be allocated, the object 158pointed to by 159.Fa ptr 160is unchanged. 161If 162.Fa size 163is zero and 164.Fa ptr 165is not a null pointer, the object it points to is freed and a new zero size 166object is returned. 167.Pp 168When using 169.Fn realloc 170be careful to avoid the following idiom: 171.Bd -literal -offset indent 172size += 50; 173if ((p = realloc(p, size)) == NULL) 174 return (NULL); 175.Ed 176.Pp 177Do not adjust the variable describing how much memory has been allocated 178until the allocation has been successful. 179This can cause aberrant program behavior if the incorrect size value is used. 180In most cases, the above sample will also result in a leak of memory. 181As stated earlier, a return value of 182.Dv NULL 183indicates that the old object still remains allocated. 184Better code looks like this: 185.Bd -literal -offset indent 186newsize = size + 50; 187if ((newp = realloc(p, newsize)) == NULL) { 188 free(p); 189 p = NULL; 190 size = 0; 191 return (NULL); 192} 193p = newp; 194size = newsize; 195.Ed 196.Pp 197As with 198.Fn malloc 199it is important to ensure the new size value will not overflow; 200i.e. avoid allocations like the following: 201.Bd -literal -offset indent 202if ((newp = realloc(p, num * size)) == NULL) { 203 ... 204.Ed 205.Sh MALLOC_OPTIONS 206Malloc will first look for a symbolic link called 207.Pa /etc/malloc.conf 208and next check the environment for a variable called 209.Ev MALLOC_OPTIONS 210and finally for the global variable 211.Va malloc_options 212and scan them for flags in that order. 213Flags are single letters, uppercase means on, lowercase means off. 214.Bl -tag -width indent 215.It Cm A 216.Dq Abort . 217.Fn malloc 218will coredump the process, rather than tolerate internal 219inconsistencies or incorrect usage. 220This is the default and a very handy debugging aid, 221since the core file represents the time of failure, 222rather than when the bogus pointer was used. 223.It Cm D 224.Dq Dump . 225.Fn malloc 226will dump statistics to the file 227.Pa ./malloc.out , 228if it already exists, 229at exit. 230This option requires the library to have been compiled with -DMALLOC_STATS in 231order to have any effect. 232.It Cm F 233.Dq Freeguard . 234Enable use after free detection. 235Unused pages on the freelist are read and write protected to 236cause a segmentation fault upon access. 237This will also switch off the delayed freeing of chunks, 238reducing random behaviour but detecting double 239.Fn free 240calls as early as possible. 241This option is intended for debugging rather than improved security 242(use the 243.Cm U 244option for security). 245.It Cm G 246.Dq Guard . 247Enable guard pages. 248Each page size or larger allocation is followed by a guard page that will 249cause a segmentation fault upon any access. 250.It Cm H 251.Dq Hint . 252Pass a hint to the kernel about pages we don't use. 253If the machine is paging a lot this may help a bit. 254.It Cm J 255.Dq Junk . 256Fill some junk into the area allocated. 257Currently junk is bytes of 0xd0 when allocating; this is pronounced 258.Dq Duh . 259\&:-) 260Freed chunks are filled with 0xdf. 261.It Cm P 262.Dq Move allocations within a page. 263Allocations larger than half a page but smaller than a page 264are aligned to the end of a page to catch buffer overruns in more 265cases. 266This is the default. 267.It Cm R 268.Dq realloc . 269Always reallocate when 270.Fn realloc 271is called, even if the initial allocation was big enough. 272This can substantially aid in compacting memory. 273.\".Pp 274.\".It Cm U 275.\".Dq utrace . 276.\"Generate entries for 277.\".Xr ktrace 1 278.\"for all operations. 279.\"Consult the source for this one. 280.It Cm S 281Enable all options suitable for security auditing. 282.It Cm U 283.Dq Free unmap . 284Enable use after free protection for larger allocations. 285Unused pages on the freelist are read and write protected to 286cause a segmentation fault upon access. 287.It Cm X 288.Dq xmalloc . 289Rather than return failure, 290.Xr abort 3 291the program with a diagnostic message on stderr. 292It is the intention that this option be set at compile time by 293including in the source: 294.Bd -literal -offset indent 295extern char *malloc_options; 296malloc_options = "X"; 297.Ed 298.Pp 299Note that this will cause code that is supposed to handle 300out-of-memory conditions gracefully to abort instead. 301.It Cm Z 302.Dq Zero . 303Fill some junk into the area allocated (see 304.Cm J ) , 305except for the exact length the user asked for, which is zeroed. 306.It Cm < 307.Dq Half the cache size . 308Decrease the size of the free page cache by a factor of two. 309.It Cm > 310.Dq Double the cache size . 311Increase the size of the free page cache by a factor of two. 312.El 313.Pp 314So to set a systemwide reduction of the cache to a quarter of the 315default size and use guard pages: 316.Dl # ln -s 'G\*(Lt\*(Lt' /etc/malloc.conf 317.Pp 318The flags are mostly for testing and debugging. 319If a program changes behavior if any of these options (except 320.Cm X ) 321are used, 322it is buggy. 323.Pp 324The default number of free pages cached is 64. 325.Sh RETURN VALUES 326The 327.Fn malloc 328and 329.Fn calloc 330functions return a pointer to the allocated space if successful; otherwise, 331a null pointer is returned and 332.Va errno 333is set to 334.Er ENOMEM . 335.Pp 336The 337.Fn free 338and 339.Fn cfree 340functions return no value. 341.Pp 342The 343.Fn realloc 344function returns a pointer to the (possibly moved) allocated space 345if successful; otherwise, a null pointer is returned and 346.Va errno 347is set to 348.Er ENOMEM . 349.Sh ENVIRONMENT 350.Bl -tag -width Ev 351.It Ev MALLOC_OPTIONS 352See above. 353.El 354.Sh FILES 355.Bl -tag -width "/etc/malloc.conf" 356.It Pa /etc/malloc.conf 357symbolic link to filename containing option flags 358.El 359.Sh DIAGNOSTICS 360If 361.Fn malloc , 362.Fn calloc , 363.Fn realloc , 364or 365.Fn free 366detect an error condition, 367a message will be printed to file descriptor 3682 (not using stdio). 369Errors will result in the process being aborted, 370unless the 371.Cm a 372option has been specified. 373.Pp 374Here is a brief description of the error messages and what they mean: 375.Bl -tag -width Ds 376.It Dq out of memory 377If the 378.Cm X 379option is specified it is an error for 380.Fn malloc , 381.Fn calloc , 382or 383.Fn realloc 384to return 385.Dv NULL . 386.It Dq malloc init mmap failed 387This is a rather weird condition that is most likely to indicate a 388seriously overloaded system or a ulimit restriction. 389.It Dq bogus pointer (double free?) 390An attempt to 391.Fn free 392or 393.Fn realloc 394an unallocated pointer was made. 395.It Dq chunk is already free 396There was an attempt to free a chunk that had already been freed. 397.It Dq modified chunk-pointer 398The pointer passed to 399.Fn free 400or 401.Fn realloc 402has been modified. 403.It Dq recursive call 404An attempt was made to call recursively into these functions, i.e., from a 405signal handler. 406This behavior is not supported. 407In particular, signal handlers should 408.Em not 409use any of the 410.Fn malloc 411functions nor utilize any other functions which may call 412.Fn malloc 413(e.g., 414.Xr stdio 3 415routines). 416.It Dq unknown char in MALLOC_OPTIONS 417We found something we didn't understand. 418.It Dq malloc cache overflow/underflow 419The internal malloc page cache has been corrupted. 420.It Dq malloc free slot lost 421The internal malloc page cache has been corrupted. 422.It Dq guard size 423An inconsistent guard size was detected. 424.It any other error 425.Fn malloc 426detected an internal error; 427consult sources and/or wizards. 428.El 429.Sh SEE ALSO 430.Xr brk 2 , 431.Xr mmap 2 , 432.Xr munmap 2 , 433.Xr alloca 3 , 434.Xr getpagesize 3 , 435.Xr posix_memalign 3 436.Sh STANDARDS 437The 438.Fn malloc 439function conforms to 440.St -ansiC . 441.Sh HISTORY 442The 443.Nm 444family of functions first appeared in 445.At v7 . 446A new implementation by Chris Kingsley was introduced in 447.Bx 4.2 , 448followed by a complete rewrite by Poul-Henning Kamp which appeared in 449.Fx 2.2 450and was included in 451.Ox 2.0 . 452These implementations were all 453.Xr sbrk 2 454based. 455In 456.Ox 3.8 , 457Thierry Deval rewrote 458.Nm 459to use the 460.Xr mmap 2 461system call, 462making the page addresses returned by 463.Nm 464random. 465A rewrite by Otto Moerbeek introducing a new central data structure and more 466randomization appeared in 467.Ox 4.4 . 468