1.\" $NetBSD: malloc.3,v 1.19 2003/04/16 13:34:46 wiz Exp $ 2.\" 3.\" Copyright (c) 1980, 1991, 1993 4.\" The Regents of the University of California. All rights reserved. 5.\" 6.\" This code is derived from software contributed to Berkeley by 7.\" the American National Standards Committee X3, on Information 8.\" Processing Systems. 9.\" 10.\" Redistribution and use in source and binary forms, with or without 11.\" modification, are permitted provided that the following conditions 12.\" are met: 13.\" 1. Redistributions of source code must retain the above copyright 14.\" notice, this list of conditions and the following disclaimer. 15.\" 2. Redistributions in binary form must reproduce the above copyright 16.\" notice, this list of conditions and the following disclaimer in the 17.\" documentation and/or other materials provided with the distribution. 18.\" 3. All advertising materials mentioning features or use of this software 19.\" must display the following acknowledgement: 20.\" This product includes software developed by the University of 21.\" California, Berkeley and its contributors. 22.\" 4. Neither the name of the University nor the names of its contributors 23.\" may be used to endorse or promote products derived from this software 24.\" without specific prior written permission. 25.\" 26.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 27.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 28.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 29.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 30.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 31.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 32.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 33.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 34.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 35.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 36.\" SUCH DAMAGE. 37.\" 38.\" @(#)malloc.3 8.1 (Berkeley) 6/4/93 39.\" From FreeBSD: Id: malloc.3,v 1.18 1999/03/28 14:16:04 phk Exp 40.\" 41.Dd August 11, 2002 42.Dt MALLOC 3 43.Os 44.Sh NAME 45.Nm malloc , 46.Nm calloc , 47.Nm realloc , 48.Nm free 49.\"XXX", 50.\"XXX".Nm reallocf 51.Nd general purpose memory allocation functions 52.Sh LIBRARY 53.Lb libc 54.Sh SYNOPSIS 55.In stdlib.h 56.Ft void * 57.Fn malloc "size_t size" 58.Ft void * 59.Fn calloc "size_t number" "size_t size" 60.Ft void * 61.Fn realloc "void *ptr" "size_t size" 62.\"XXX".Ft void * 63.\"XXX".Fn reallocf "void *ptr" "size_t size" 64.Ft void 65.Fn free "void *ptr" 66.Ft char * 67.Va malloc_options ; 68.Sh DESCRIPTION 69The 70.Fn malloc 71function allocates 72.Fa size 73bytes of memory. 74The allocated space is suitably aligned (after possible pointer coercion) 75for storage of any type of object. 76If the space is at least 77.Em pagesize 78bytes in length (see 79.Xr getpagesize 3 ) , 80the returned memory will be page boundary aligned as well. 81If 82.Fn malloc 83fails, a 84.Dv NULL 85pointer is returned, and the errno variable is set to 86.Er ENOMEM . 87.Pp 88The 89.Fn calloc 90function allocates space for 91.Fa number 92objects, 93each 94.Fa size 95bytes in length. 96The result is identical to calling 97.Fn malloc 98with an argument of 99.Dq "number * size" , 100with the exception that the allocated memory is initialized to all bits zero. 101.Pp 102The 103.Fn realloc 104function changes the size of the previously allocated memory referenced by 105.Fa ptr 106to 107.Fa size 108bytes and returns a pointer to the (possibly moved) object. 109The contents of the memory are unchanged up to the lesser of the new and 110old sizes. 111If the new size is larger, 112the value of the newly allocated portion of the memory is undefined. 113If the requested memory cannot be allocated, 114.Dv NULL 115is returned and the memory referenced by 116.Fa ptr 117is valid and unchanged. 118If 119.Fa ptr 120is 121.Dv NULL , 122the 123.Fn realloc 124function behaves identically to 125.Fn malloc 126for the specified size. 127.Pp 128When using 129.Fn realloc 130one must be careful to avoid the following idiom: 131.Pp 132.Bd -literal -offset indent 133if ((p = realloc(p, nsize)) == NULL) 134 return NULL; 135.Ed 136.Pp 137In most cases, this will result in a leak of memory. 138As stated earlier, a return value of 139.Dv NULL 140indicates that the old object still remains allocated. 141Better code looks like this: 142.Bd -literal -offset indent 143if ((p2 = realloc(p, nsize)) == NULL) { 144 if (p) 145 free(p); 146 p = NULL; 147 return NULL; 148} 149p = p2; 150.Ed 151.\"XXX".Pp 152.\"XXX"The 153.\"XXX".Fn reallocf 154.\"XXX"function call is identical to the realloc function call, except that it 155.\"XXX"will free the passed pointer when the requested memory cannot be allocated. 156.\"XXX"This is a FreeBSD 157.\"XXX"specific API designed to ease the problems with traditional coding styles 158.\"XXX"for realloc causing memory leaks in libraries. 159.Pp 160The 161.Fn free 162function causes the allocated memory referenced by 163.Fa ptr 164to be made available for future allocations. 165If 166.Fa ptr 167is 168.Dv NULL , 169no action occurs. 170.Sh TUNING 171Once, when the first call is made to one of these memory allocation 172routines, various flags will be set or reset, which affect the 173workings of this allocation implementation. 174.Pp 175The ``name'' of the file referenced by the symbolic link named 176.Pa /etc/malloc.conf , 177the value of the environment variable 178.Ev MALLOC_OPTIONS , 179and the string pointed to by the global variable 180.Va malloc_options 181will be interpreted, in that order, character by character as flags. 182.Pp 183Most flags are single letters, 184where uppercase indicates that the behavior is set, or on, 185and lowercase means that the behavior is not set, or off. 186.Bl -tag -width indent 187.It A 188All warnings (except for the warning about unknown 189flags being set), and failure to allocate memory become fatal. 190The process will call 191.Fn abort 3 192in these cases. 193.It J 194Each byte of new memory allocated by 195.\"XXX".Fn malloc , 196.\"XXX".Fn realloc 197.\"XXX"or 198.\"XXX".Fn reallocf 199.Fn malloc 200or 201.Fn realloc 202as well as all memory returned by 203.\"XXX".Fn free , 204.\"XXX".Fn realloc 205.\"XXX"or 206.\"XXX"Fn reallocf 207.Fn free 208or 209.Fn realloc 210will be initialized to 0xd0. 211This options also sets the 212.Dq R 213option. 214This is intended for debugging and will impact performance negatively. 215.It H 216Pass a hint to the kernel about pages unused by the allocation functions. 217This will help performance if the system is paging excessively. 218This option is off by default. 219.It R 220Causes the 221.Fn realloc 222.\"XXX"and 223.\"XXX".Fn reallocf 224.\"XXX"functions 225function 226to always reallocate memory even if the initial allocation was 227sufficiently large. 228This can substantially aid in compacting memory. 229.It U 230Generate 231.Dq utrace 232entries for 233.Xr ktrace 1 , 234for all operations. 235Consult the source for details on this option. 236.It V 237Attempting to allocate zero bytes will return a 238.Dv NULL 239pointer instead of a valid pointer. 240(The default behavior is to make a minimal allocation and return a 241pointer to it.) 242This option is provided for System V compatibility. 243.It X 244Rather than return failure for any allocation function, 245display a diagnostic message on stderr and cause the program to drop 246core (using 247.Fn abort 3 ) . 248This option should be set at compile time by including the following in 249the source code: 250.Bd -literal -offset indent 251extern char *malloc_options; 252malloc_options = "X"; 253.Ed 254.It Z 255This option implicitly sets the 256.Dq J 257and 258.Dq R 259options, and then zeros out the bytes that were requested. 260This is intended for debugging and will impact performance negatively. 261.It \*[Lt] 262Reduce the size of the cache by a factor of two. 263The default cache size is 16 pages. 264This option can be specified multiple times. 265.It \*[Gt] 266Double the size of the cache by a factor of two. 267The default cache size is 16 pages. 268This option can be specified multiple times. 269.El 270.Pp 271The 272.Dq J 273and 274.Dq Z 275options are intended for testing and debugging. 276An application which changes its behavior when these options are used 277is flawed. 278.Sh RETURN VALUES 279The 280.Fn malloc 281and 282.Fn calloc 283functions return a pointer to the allocated memory if successful; otherwise a 284.Dv NULL 285pointer is returned and 286.Va errno 287is set to 288.Er ENOMEM . 289.Pp 290The 291.Fn realloc 292.\"XXX"and 293.\"XXX".Fn reallocf 294.\"XXX"functions return 295function returns 296a pointer, possibly identical to 297.Fa ptr , 298to the allocated memory if successful; otherwise a 299.Dv NULL 300pointer is returned and 301.Va errno 302is set to 303.Er ENOMEM , 304in which case the 305memory referenced by 306.Fa ptr 307is still available and intact. 308.Pp 309The 310.Fn free 311function returns no value. 312.Sh ENVIRONMENT 313The following environment variables affect the execution of the allocation 314functions: 315.Bl -tag -width MMM 316.It Ev MALLOC_OPTIONS 317If the environment variable 318.Ev MALLOC_OPTIONS 319is set, the characters it contains will be interpreted as flags to the 320allocation functions. 321.El 322.Sh FILES 323.Bl -tag -width "/etc/malloc.conf" 324.It Pa /etc/malloc.conf 325symbolic link to filename containing option flags 326.El 327.Sh EXAMPLES 328To set a systemwide reduction of cache size, and to dump core whenever 329a problem occurs: 330.Pp 331.Bd -literal -offset indent 332ln -s 'A\*[Lt]' /etc/malloc.conf 333.Ed 334.Pp 335To specify in the source that a program does no return value checking 336on calls to these functions: 337.Bd -literal -offset indent 338extern char *malloc_options; 339malloc_options = "X"; 340.Ed 341.Sh DEBUGGING MALLOC PROBLEMS 342The major difference between this implementation and other allocation 343implementations is that the free pages are not accessed unless allocated, 344and are aggressively returned to the kernel for reuse. 345.Bd -filled -offset indent 346Most allocation implementations will store a data structure containing a 347linked list in the free chunks of memory, 348used to tie all the free memory together. 349That can be suboptimal, 350as every time the free-list is traversed, 351the otherwise unused, and likely paged out, 352pages are faulted into primary memory. 353On systems which are paging, 354this can result in a factor of five increase in the number of page-faults 355done by a process. 356.Ed 357.Pp 358A side effect of this architecture is that many minor transgressions on 359the interface which would traditionally not be detected are in fact detected. 360As a result, programs that have been running happily for 361years may suddenly start to complain loudly, when linked with this 362allocation implementation. 363.Pp 364The first and most important thing to do is to set the 365.Dq A 366option. 367This option forces a coredump (if possible) at the first sign of trouble, 368rather than the normal policy of trying to continue if at all possible. 369.Pp 370It is probably also a good idea to recompile the program with suitable 371options and symbols for debugger support. 372.Pp 373If the program starts to give unusual results, coredump or generally behave 374differently without emitting any of the messages listed in the next section, 375it is likely because it depends on the storage being filled with nul bytes. 376Try running it with 377.Dq Z 378option set; 379if that improves the situation, this diagnosis has been confirmed. 380If the program still misbehaves, 381the likely problem is accessing memory outside the allocated area, 382more likely after than before the allocated area. 383.Pp 384Alternatively, if the symptoms are not easy to reproduce, setting the 385.Dq J 386option may help provoke the problem. 387.Pp 388In truly difficult cases, the 389.Dq U 390option, if supported by the kernel, can provide a detailed trace of 391all calls made to these functions. 392.Pp 393Unfortunately this implementation does not provide much detail about 394the problems it detects, the performance impact for storing such information 395would be prohibitive. 396There are a number of allocation implementations available on the 'Net 397which focus on detecting and pinpointing problems by trading performance 398for extra sanity checks and detailed diagnostics. 399.Sh DIAGNOSTIC MESSAGES 400If 401.Fn malloc , 402.Fn calloc , 403.Fn realloc 404or 405.Fn free 406detect an error or warning condition, 407a message will be printed to file descriptor STDERR_FILENO. 408Errors will result in the process dumping core. 409If the 410.Dq A 411option is set, all warnings are treated as errors. 412.Pp 413The following is a brief description of possible error messages and 414their meanings: 415.Pp 416.Bl -tag -width indent 417.It "(ES): mumble mumble mumble 418The allocation functions were compiled with 419.Dq EXTRA_SANITY 420defined, and an error was found during the additional error checking. 421Consult the source code for further information. 422.It "allocation failed 423If the 424.Dq A 425option is specified it is a fatal error for an allocation function to fail. 426.It "mmap(2) failed, check limits 427This most likely means that the system is dangerously overloaded or that 428the process' limits are incorrectly specified. 429.It "freelist is destroyed 430The internal free-list has been corrupted. 431.El 432.Pp 433.Bl -tag -width indent 434The following is a brief description of possible warning messages and 435their meanings: 436.Pp 437.It "chunk/page is already free 438The process attempted to 439.Fn free 440memory which had already been freed. 441.It "junk pointer ... 442A pointer specified to one of the allocation functions points outside the 443bounds of the memory of which they are aware. 444.It "malloc() has never been called 445No memory has been allocated, 446yet something is being freed or 447realloc'ed. 448.It "modified (chunk-/page-) pointer 449The pointer passed to 450.Fn free 451or 452.Fn realloc 453has been modified. 454.It "pointer to wrong page 455The pointer that 456.Fn malloc 457or 458.Fn calloc 459is trying to free does not reference a possible page. 460.It "recursive call 461A process has attempted to call an allocation function recursively. 462This is not permitted. 463In particular, signal handlers should not attempt to allocate memory. 464.It "out of memory 465The 466.Dq X 467option was specified and an allocation of memory failed. 468.It "unknown char in MALLOC_OPTIONS 469An unknown option was specified. 470Even with the 471.Dq A 472option set, this warning is still only a warning. 473.El 474.Sh SEE ALSO 475.Xr brk 2 , 476.Xr alloca 3 , 477.Xr getpagesize 3 , 478.Xr memory 3 479.\"XXX" .Pa /usr/share/doc/papers/malloc.ascii.gz 480.Sh STANDARDS 481The 482.Fn malloc , 483.Fn calloc , 484.Fn realloc 485and 486.Fn free 487functions conform to 488.St -ansiC . 489.Sh HISTORY 490The present allocation implementation started out as a filesystem for a 491drum attached to a 20bit binary challenged computer which was built 492with discrete germanium transistors. 493It has since graduated to handle primary storage rather than secondary. 494It first appeared in its new shape and ability in 495.Fx 2.2 , and then in 496.Nx 1.5 . 497.Sh BUGS 498The messages printed in case of problems provide no detail about the 499actual values. 500.Pp 501It can be argued that returning a null pointer when asked to 502allocate zero bytes is a silly response to a silly question. 503.Pp 504This implementation was authored by Poul-Henning Kamp. 505Please report any problems to him at 506.Aq phk@FreeBSD.org . 507