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.37 2004/07/02 10:42:55 jmc 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.Pp 186.It Cm D 187.Dq Dump . 188.Fn malloc 189will dump statistics in a file called 190.Pa malloc.out 191at exit. 192This option requires the library to have been compiled with -DMALLOC_STATS in 193order to have any effect. 194.Pp 195.It Cm F 196.Dq Freeguard . 197Enable use after free protection. 198Unused pages on the freelist are read and write protected to 199cause a segmentation fault upon access. 200.Pp 201.It Cm G 202.Dq Guard . 203Enable guard pages and chunk randomization. 204Each page size or larger allocation is followed by a guard page that will 205cause a segmentation fault upon any access. 206Smaller than page size chunks are returned in a random order. 207.Pp 208.It Cm H 209.Dq Hint . 210Pass a hint to the kernel about pages we don't use. 211If the machine is paging a lot this may help a bit. 212.Pp 213.It Cm J 214.Dq Junk . 215Fill some junk into the area allocated. 216Currently junk is bytes of 0xd0; this is pronounced 217.Dq Duh . 218\&:-) 219.Pp 220.It Cm N 221Do not output warning messages when encountering possible corruption 222or bad pointers. 223.Pp 224.It Cm R 225.Dq realloc . 226Always reallocate when 227.Fn realloc 228is called, even if the initial allocation was big enough. 229This can substantially aid in compacting memory. 230.\".Pp 231.\".It Cm U 232.\".Dq utrace . 233.\"Generate entries for 234.\".Xr ktrace 1 235.\"for all operations. 236.\"Consult the source for this one. 237.Pp 238.It Cm X 239.Dq xmalloc . 240Rather than return failure, 241.Xr abort 3 242the program with a diagnostic message on stderr. 243It is the intention that this option be set at compile time by 244including in the source: 245.Bd -literal -offset indent 246extern char *malloc_options; 247malloc_options = "X"; 248.Ed 249.Pp 250.It Cm Z 251.Dq Zero . 252Fill some junk into the area allocated (see 253.Cm J ) , 254except for the exact length the user asked for, which is zeroed. 255.Pp 256.It Cm < 257.Dq Half the cache size . 258Reduce the size of the cache by a factor of two. 259.Pp 260.It Cm > 261.Dq Double the cache size . 262Double the size of the cache by a factor of two. 263.El 264.Pp 265So to set a systemwide reduction of cache size and coredumps on problems 266one would: 267.Li ln -s 'A<' /etc/malloc.conf 268.Pp 269The 270.Cm J 271and 272.Cm Z 273flags are mostly for testing and debugging. 274If a program changes behavior if either of these options are used, 275it is buggy. 276.Pp 277The default cache size is 16 pages. 278.Sh RETURN VALUES 279The 280.Fn malloc 281and 282.Fn calloc 283functions return a pointer to the allocated space if successful; otherwise, 284a null pointer is returned and 285.Va errno 286is set to 287.Er ENOMEM . 288.Pp 289The 290.Fn free 291and 292.Fn cfree 293functions return no value. 294.Pp 295The 296.Fn realloc 297function returns a pointer to the (possibly moved) allocated space 298if successful; otherwise, a null pointer is returned and 299.Va errno 300is set to 301.Er ENOMEM . 302.Sh ENVIRONMENT 303See above. 304.Sh FILES 305.Bl -tag -width "/etc/malloc.conf" 306.It Pa /etc/malloc.conf 307symbolic link to filename containing option flags 308.El 309.Sh DIAGNOSTICS 310If 311.Fn malloc , 312.Fn calloc , 313.Fn realloc , 314or 315.Fn free 316detect an error or warning condition, 317a message will be printed to file descriptor 3182 (not using stdio). 319Errors will always result in the process being 320.Xr abort 3 'ed. 321If the 322.Cm A 323option has been specified, warnings will also 324.Xr abort 3 325the process. 326.Pp 327Here is a brief description of the error messages and what they mean: 328.Bl -tag -width Fl 329.It Dq (ES): mumble mumble mumble 330.Fn malloc 331has been compiled with 332.Dv \&-DEXTRA_SANITY 333and something looks fishy in there. 334Consult sources and/or wizards. 335.It Dq allocation failed 336If the 337.Cm A 338option is specified it is an error for 339.Fn malloc , 340.Fn calloc , 341or 342.Fn realloc 343to return 344.Dv NULL . 345.It Dq mmap(2) failed, check limits. 346This is a rather weird condition that is most likely to indicate a 347seriously overloaded system or a 348.Xr ulimit 1 349restriction. 350.It Dq freelist is destroyed. 351.Fn malloc Ns 's 352internal freelist has been stomped on. 353.El 354.Pp 355Here is a brief description of the warning messages and what they mean: 356.Bl -tag -width Fl 357.It Dq chunk/page is already free. 358There was an attempt to free a chunk that had already been freed. 359.It Dq junk pointer, too high to make sense. 360The pointer doesn't make sense. 361It's above the area of memory that 362.Fn malloc 363knows something about. 364This could be a pointer from some 365.Xr mmap 2 'ed 366memory. 367.It Dq junk pointer, too low to make sense. 368The pointer doesn't make sense. 369It's below the area of memory that 370.Fn malloc 371knows something about. 372This pointer probably came from your data or bss segments. 373.It Dq malloc() has never been called. 374Nothing has ever been allocated, yet something is being freed or 375realloc'ed. 376.It Dq modified (chunk-/page-) pointer. 377The pointer passed to free or realloc has 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