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.41 2005/07/26 04:20:23 jaredy Exp $ 34.\" 35.Dd August 27, 1996 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 86The 87.Fn calloc 88function allocates space for an array of 89.Fa nmemb 90objects, each of whose size is 91.Fa size . 92The space is initialized to all bits zero. 93.Pp 94The 95.Fn free 96function causes the space pointed to by 97.Fa ptr 98to be deallocated, that is, at least made available for further allocation, 99but if possible, it will passed back to the kernel with 100.Xr sbrk 2 . 101If 102.Fa ptr 103is a null pointer, no action occurs. 104.Pp 105A 106.Fn cfree 107function is also provided for compatibility with old systems and other 108.Nm malloc 109libraries; it is simply an alias for 110.Fn free . 111.Pp 112The 113.Fn realloc 114function changes the size of the object pointed to by 115.Fa ptr 116to 117.Fa size 118bytes and returns a pointer to the (possibly moved) object. 119The contents of the object are unchanged up to the lesser 120of the new and old sizes. 121If the new size is larger, the value of the newly allocated portion 122of the object is indeterminate and uninitialized. 123If 124.Fa ptr 125is a null pointer, the 126.Fn realloc 127function behaves like the 128.Fn malloc 129function for the specified size. 130If the space cannot be allocated, the object 131pointed to by 132.Fa ptr 133is unchanged. 134If 135.Fa size 136is zero and 137.Fa ptr 138is not a null pointer, the object it points to is freed and a new zero size 139object is returned. 140.Pp 141When using 142.Fn realloc 143one must be careful to avoid the following idiom: 144.Bd -literal -offset indent 145size += 50; 146if ((p = realloc(p, size)) == NULL) 147 return (NULL); 148.Ed 149.Pp 150Do not adjust the variable describing how much memory has been allocated 151until one knows the allocation has been successful. 152This can cause aberrant program behavior if the incorrect size value is used. 153In most cases, the above sample will also result in a leak of memory. 154As stated earlier, a return value of 155.Dv NULL 156indicates that the old object still remains allocated. 157Better code looks like this: 158.Bd -literal -offset indent 159newsize = size + 50; 160if ((newp = realloc(p, newsize)) == NULL) { 161 free(p); 162 p = NULL; 163 size = 0; 164 return (NULL); 165} 166p = newp; 167size = newsize; 168.Ed 169.Pp 170Malloc will first look for a symbolic link called 171.Pa /etc/malloc.conf 172and next check the environment for a variable called 173.Ev MALLOC_OPTIONS 174and finally for the global variable 175.Va malloc_options 176and scan them for flags in that order. 177Flags are single letters, uppercase means on, lowercase means off. 178.Bl -tag -width indent 179.It Cm A 180.Dq Abort . 181.Fn malloc 182will coredump the process, rather than tolerate failure. 183This is a very handy debugging aid, since the core file will represent the 184time of failure, rather than when the null pointer was accessed. 185.It Cm D 186.Dq Dump . 187.Fn malloc 188will dump statistics in a file called 189.Pa malloc.out 190at exit. 191This option requires the library to have been compiled with -DMALLOC_STATS in 192order to have any effect. 193.It Cm F 194.Dq Freeguard . 195Enable use after free protection. 196Unused pages on the freelist are read and write protected to 197cause a segmentation fault upon access. 198.It Cm G 199.Dq Guard . 200Enable guard pages and chunk randomization. 201Each page size or larger allocation is followed by a guard page that will 202cause a segmentation fault upon any access. 203Smaller than page size chunks are returned in a random order. 204.It Cm H 205.Dq Hint . 206Pass a hint to the kernel about pages we don't use. 207If the machine is paging a lot this may help a bit. 208.It Cm J 209.Dq Junk . 210Fill some junk into the area allocated. 211Currently junk is bytes of 0xd0; this is pronounced 212.Dq Duh . 213\&:-) 214.It Cm N 215Do not output warning messages when encountering possible corruption 216or bad pointers. 217.It Cm P 218.Dq Pointer Protection . 219Pointer sized allocations are aligned to the end of a page to catch 220sizeof(ptr) errors where sizeof(*ptr) is meant. 221.It Cm R 222.Dq realloc . 223Always reallocate when 224.Fn realloc 225is called, even if the initial allocation was big enough. 226This can substantially aid in compacting memory. 227.\".Pp 228.\".It Cm U 229.\".Dq utrace . 230.\"Generate entries for 231.\".Xr ktrace 1 232.\"for all operations. 233.\"Consult the source for this one. 234.It Cm X 235.Dq xmalloc . 236Rather than return failure, 237.Xr abort 3 238the program with a diagnostic message on stderr. 239It is the intention that this option be set at compile time by 240including in the source: 241.Bd -literal -offset indent 242extern char *malloc_options; 243malloc_options = "X"; 244.Ed 245.It Cm Z 246.Dq Zero . 247Fill some junk into the area allocated (see 248.Cm J ) , 249except for the exact length the user asked for, which is zeroed. 250.It Cm < 251.Dq Half the cache size . 252Reduce the size of the cache by a factor of two. 253.It Cm > 254.Dq Double the cache size . 255Double the size of the cache by a factor of two. 256.El 257.Pp 258So to set a systemwide reduction of cache size and coredumps on problems 259one would: 260.Li ln -s 'A<' /etc/malloc.conf 261.Pp 262The 263.Cm J 264and 265.Cm Z 266flags are mostly for testing and debugging. 267If a program changes behavior if either of these options are used, 268it is buggy. 269.Pp 270The default cache size is 16 pages. 271.Sh RETURN VALUES 272The 273.Fn malloc 274and 275.Fn calloc 276functions return a pointer to the allocated space if successful; otherwise, 277a null pointer is returned and 278.Va errno 279is set to 280.Er ENOMEM . 281.Pp 282The 283.Fn free 284and 285.Fn cfree 286functions return no value. 287.Pp 288The 289.Fn realloc 290function returns a pointer to the (possibly moved) allocated space 291if successful; otherwise, a null pointer is returned and 292.Va errno 293is set to 294.Er ENOMEM . 295.Sh ENVIRONMENT 296.Bl -tag -width Ev 297.It Ev MALLOC_OPTIONS 298See above. 299.El 300.Sh FILES 301.Bl -tag -width "/etc/malloc.conf" 302.It Pa /etc/malloc.conf 303symbolic link to filename containing option flags 304.El 305.Sh DIAGNOSTICS 306If 307.Fn malloc , 308.Fn calloc , 309.Fn realloc , 310or 311.Fn free 312detect an error or warning condition, 313a message will be printed to file descriptor 3142 (not using stdio). 315Errors will always result in the process being 316.Xr abort 3 'ed. 317If the 318.Cm A 319option has been specified, warnings will also 320.Xr abort 3 321the process. 322.Pp 323Here is a brief description of the error messages and what they mean: 324.Bl -tag -width Ds 325.It Dq (ES): mumble mumble mumble 326.Fn malloc 327has been compiled with 328.Dv \&-DEXTRA_SANITY 329and something looks fishy in there. 330Consult sources and/or wizards. 331.It Dq allocation failed 332If the 333.Cm A 334option is specified it is an error for 335.Fn malloc , 336.Fn calloc , 337or 338.Fn realloc 339to return 340.Dv NULL . 341.It Dq mmap(2) failed, check limits. 342This is a rather weird condition that is most likely to indicate a 343seriously overloaded system or a 344.Xr ulimit 1 345restriction. 346.It Dq freelist is destroyed. 347.Fn malloc Ns 's 348internal freelist has been stomped on. 349.El 350.Pp 351Here is a brief description of the warning messages and what they mean: 352.Bl -tag -width Ds 353.It Dq chunk/page is already free. 354There was an attempt to free a chunk that had already been freed. 355.It Dq junk pointer, too high to make sense. 356The pointer doesn't make sense. 357It's above the area of memory that 358.Fn malloc 359knows something about. 360This could be a pointer from some 361.Xr mmap 2 'ed 362memory. 363.It Dq junk pointer, too low to make sense. 364The pointer doesn't make sense. 365It's below the area of memory that 366.Fn malloc 367knows something about. 368This pointer probably came from your data or bss segments. 369.It Dq malloc() has never been called. 370Nothing has ever been allocated, yet something is being freed or 371realloc'ed. 372.It Dq modified (chunk-/page-) pointer. 373The pointer passed to 374.Fn free 375or 376.Fn realloc 377has been modified. 378.It Dq pointer to wrong page. 379The pointer that 380.Fn malloc 381is trying to free is not pointing to 382a sensible page. 383.It Dq recursive call. 384An attempt was made to call recursively into these functions, i.e., from a 385signal handler. 386This behavior is not supported. 387In particular, signal handlers should 388.Em not 389use any of the 390.Fn malloc 391functions nor utilize any other functions which may call 392.Fn malloc 393(e.g., 394.Xr stdio 3 395routines). 396.It Dq unknown char in MALLOC_OPTIONS 397We found something we didn't understand. 398.El 399.Sh SEE ALSO 400.Xr brk 2 , 401.Xr alloca 3 , 402.Xr getpagesize 3 403.Sh STANDARDS 404The 405.Fn malloc 406function conforms to 407.St -ansiC . 408.Sh HISTORY 409The present implementation of 410.Fn malloc 411started out as a filesystem on a drum 412attached to a 20-bit binary challenged computer built with discrete germanium 413transistors, and it has since graduated to handle primary storage rather than 414secondary. 415.Pp 416The main difference from other 417.Fn malloc 418implementations are believed to be that 419the free pages are not accessed until allocated. 420Most 421.Fn malloc 422implementations will store a data structure containing a, 423possibly double-, linked list in the free chunks of memory, used to tie 424all the free memory together. 425That is a quite suboptimal thing to do. 426Every time the free-list is traversed, all the otherwise unused, and very 427likely paged out, pages get faulted into primary memory, just to see what 428lies after them in the list. 429.Pp 430On systems which are paging, this can increase the page-faults 431of a process by a factor of five. 432