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.33 2003/11/25 12:32:54 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 G 196Enable guard pages and chunk randomization. 197Each page size or larger allocation is followed by a guard page that will 198cause a segmentation fault upon any access. 199Smaller than page size chunks are returned in a random order. 200.Pp 201.It Cm J 202.Dq Junk . 203Fill some junk into the area allocated. 204Currently junk is bytes of 0xd0; this is pronounced 205.Dq Duh . 206\&:-) 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 N 214Do not output warning messages when encountering possible corruption 215or bad pointers. 216.Pp 217.It Cm R 218.Dq realloc . 219Always reallocate when 220.Fn realloc 221is called, even if the initial allocation was big enough. 222This can substantially aid in compacting memory. 223.\".Pp 224.\".It Cm U 225.\".Dq utrace . 226.\"Generate entries for 227.\".Xr ktrace 1 228.\"for all operations. 229.\"Consult the source for this one. 230.Pp 231.It Cm X 232.Dq xmalloc . 233Rather than return failure, 234.Xr abort 3 235the program with a diagnostic message on stderr. 236It is the intention that this option be set at compile time by 237including in the source: 238.Bd -literal -offset indent 239extern char *malloc_options; 240malloc_options = "X"; 241.Ed 242.Pp 243.It Cm Z 244.Dq Zero . 245Fill some junk into the area allocated (see 246.Cm J ) , 247except for the exact length the user asked for, which is zeroed. 248.Pp 249.It Cm < 250.Dq Half the cache size . 251Reduce the size of the cache by a factor of two. 252.Pp 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 296See above. 297.Sh FILES 298.Bl -tag -width "/etc/malloc.conf" 299.It Pa /etc/malloc.conf 300symbolic link to filename containing option flags 301.El 302.Sh DIAGNOSTICS 303If 304.Fn malloc , 305.Fn calloc , 306.Fn realloc , 307or 308.Fn free 309detect an error or warning condition, 310a message will be printed to file descriptor 3112 (not using stdio). 312Errors will always result in the process being 313.Xr abort 3 'ed. 314If the 315.Cm A 316option has been specified, warnings will also 317.Xr abort 3 318the process. 319.Pp 320Here is a brief description of the error messages and what they mean: 321.Bl -tag -width Fl 322.It Dq (ES): mumble mumble mumble 323.Fn malloc 324has been compiled with 325.Dv \&-DEXTRA_SANITY 326and something looks fishy in there. 327Consult sources and/or wizards. 328.It Dq allocation failed 329If the 330.Cm A 331option is specified it is an error for 332.Fn malloc , 333.Fn calloc , 334or 335.Fn realloc 336to return 337.Dv NULL . 338.It Dq mmap(2) failed, check limits. 339This is a rather weird condition that is most likely to indicate a 340seriously overloaded system or a 341.Xr ulimit 1 342restriction. 343.It Dq freelist is destroyed. 344.Fn malloc Ns 's 345internal freelist has been stomped on. 346.El 347.Pp 348Here is a brief description of the warning messages and what they mean: 349.Bl -tag -width Fl 350.It Dq chunk/page is already free. 351There was an attempt to free a chunk that had already been freed. 352.It Dq junk pointer, too high to make sense. 353The pointer doesn't make sense. 354It's above the area of memory that 355.Fn malloc 356knows something about. 357This could be a pointer from some 358.Xr mmap 2 'ed 359memory. 360.It Dq junk pointer, too low to make sense. 361The pointer doesn't make sense. 362It's below the area of memory that 363.Fn malloc 364knows something about. 365This pointer probably came from your data or bss segments. 366.It Dq malloc() has never been called. 367Nothing has ever been allocated, yet something is being freed or 368realloc'ed. 369.It Dq modified (chunk-/page-) pointer. 370The pointer passed to free or realloc has been modified. 371.It Dq pointer to wrong page. 372The pointer that 373.Fn malloc 374is trying to free is not pointing to 375a sensible page. 376.It Dq recursive call. 377An attempt was made to call recursively into these functions, i.e., from a 378signal handler. 379This behavior is not supported. 380In particular, signal handlers should 381.Em not 382use any of the 383.Fn malloc 384functions nor utilize any other functions which may call 385.Fn malloc 386(e.g., 387.Xr stdio 3 388routines). 389.It Dq unknown char in MALLOC_OPTIONS 390We found something we didn't understand. 391.El 392.Sh SEE ALSO 393.Xr brk 2 , 394.Xr alloca 3 , 395.Xr getpagesize 3 , 396.Xr memory 3 397.Sh STANDARDS 398The 399.Fn malloc 400function conforms to 401.St -ansiC . 402.Sh HISTORY 403The present implementation of 404.Fn malloc 405started out as a filesystem on a drum 406attached to a 20-bit binary challenged computer built with discrete germanium 407transistors, and it has since graduated to handle primary storage rather than 408secondary. 409.Pp 410The main difference from other 411.Fn malloc 412implementations are believed to be that 413the free pages are not accessed until allocated. 414Most 415.Fn malloc 416implementations will store a data structure containing a, 417possibly double-, linked list in the free chunks of memory, used to tie 418all the free memory together. 419That is a quite suboptimal thing to do. 420Every time the free-list is traversed, all the otherwise unused, and very 421likely paged out, pages get faulted into primary memory, just to see what 422lies after them in the list. 423.Pp 424On systems which are paging, this can increase the page-faults 425of a process by a factor of five. 426