1.\" $NetBSD: malloc.3,v 1.12 2000/01/09 16:14:04 hubertf 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 2, 1999 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.Fd #include <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 NULL pointer is returned, and the errno variable is 84set to ENOMEM. 85.Pp 86The 87.Fn calloc 88function allocates space for 89.Fa number 90objects, 91each 92.Fa size 93bytes in length. 94The result is identical to calling 95.Fn malloc 96with an argument of 97.Dq "number * size" , 98with the exception that the allocated memory is initialized to all bits zero. 99.Pp 100The 101.Fn realloc 102function changes the size of the previously allocated memory referenced by 103.Fa ptr 104to 105.Fa size 106bytes. 107The contents of the memory are unchanged up to the lesser of the new and 108old sizes. 109If the new size is larger, 110the value of the newly allocated portion of the memory is undefined. 111If the requested memory cannot be allocated, NULL is returned and 112the memory referenced by 113.Fa ptr 114is valid and unchanged. 115If 116.Fa ptr 117is NULL, the 118.Fn realloc 119function behaves identically to 120.Fn malloc 121for the specified size. 122.\"XXX".Pp 123.\"XXX"The 124.\"XXX".Fn reallocf 125.\"XXX"function call is identical to the realloc function call, except that it 126.\"XXX"will free the passed pointer when the requested memory cannot be allocated. 127.\"XXX"This is a FreeBSD 128.\"XXX"specific API designed to ease the problems with traditional coding styles 129.\"XXX"for realloc causing memory leaks in libraries. 130.Pp 131The 132.Fn free 133function causes the allocated memory referenced by 134.Fa ptr 135to be made available for future allocations. 136If 137.Fa ptr 138is NULL, no action occurs. 139.Sh TUNING 140Once, when the first call is made to one of these memory allocation 141routines, various flags will be set or reset, which affect the 142workings of this allocation implementation. 143.Pp 144The ``name'' of the file referenced by the symbolic link named 145.Pa /etc/malloc.conf , 146the value of the environment variable 147.Ev MALLOC_OPTIONS , 148and the string pointed to by the global variable 149.Va malloc_options 150will be interpreted, in that order, character by character as flags. 151.Pp 152Most flags are single letters, 153where uppercase indicates that the behavior is set, or on, 154and lowercase means that the behavior is not set, or off. 155.Bl -tag -width indent 156.It A 157All warnings (except for the warning about unknown 158flags being set), and failure to allocate memory become fatal. 159The process will call 160.Fn abort 3 161in these cases. 162.It J 163Each byte of new memory allocated by 164.\"XXX".Fn malloc , 165.\"XXX".Fn realloc 166.\"XXX"or 167.\"XXX".Fn reallocf 168.Fn malloc 169or 170.Fn realloc 171as well as all memory returned by 172.\"XXX".Fn free , 173.\"XXX".Fn realloc 174.\"XXX"or 175.\"XXX"Fn reallocf 176.Fn free 177or 178.Fn realloc 179will be initialized to 0xd0. 180This options also sets the 181.Dq R 182option. 183This is intended for debugging and will impact performance negatively. 184.It H 185Pass a hint to the kernel about pages unused by the allocation functions. 186This will help performance if the system is paging excessively. This 187option is off by default. 188.It R 189Causes the 190.Fn realloc 191.\"XXX"and 192.\"XXX".Fn reallocf 193.\"XXX"functions 194function 195to always reallocate memory even if the initial allocation was 196sufficiently large. 197This can substantially aid in compacting memory. 198.It U 199Generate 200.Dq utrace 201entries for 202.Xr ktrace 1 , 203for all operations. 204Consult the source for details on this option. 205.It V 206Attempting to allocate zero bytes will return a NULL pointer instead of 207a valid pointer. 208(The default behavior is to make a minimal allocation and return a 209pointer to it.) 210This option is provided for System V compatibility. 211.It X 212Rather than return failure for any allocation function, 213display a diagnostic message on stderr and cause the program to drop 214core (using 215.Fn abort 3 ) . 216This option should be set at compile time by including the following in 217the source code: 218.Bd -literal -offset indent 219extern char *malloc_options; 220malloc_options = "X"; 221.Ed 222.It Z 223This option implicitly sets the 224.Dq J 225and 226.Dq R 227options, and then zeros out the bytes that were requested. 228This is intended for debugging and will impact performance negatively. 229.It < 230Reduce the size of the cache by a factor of two. 231The default cache size is 16 pages. 232This option can be specified multiple times. 233.It > 234Double the size of the cache by a factor of two. 235The default cache size is 16 pages. 236This option can be specified multiple times. 237.El 238.Pp 239The 240.Dq J 241and 242.Dq Z 243options are intended for testing and debugging. 244An application which changes its behavior when these options are used 245is flawed. 246.Sh EXAMPLES 247To set a systemwide reduction of cache size, and to dump core whenever 248a problem occurs: 249.Pp 250.Bd -literal -offset indent 251ln -s 'A<' /etc/malloc.conf 252.Ed 253.Pp 254To specify in the source that a program does no return value checking 255on calls to these functions: 256.Bd -literal -offset indent 257extern char *malloc_options; 258malloc_options = "X"; 259.Ed 260.Sh ENVIRONMENT 261The following environment variables affect the execution of the allocation 262functions: 263.Bl -tag -width MMM 264.It Ev MALLOC_OPTIONS 265If the environment variable 266.Ev MALLOC_OPTIONS 267is set, the characters it contains will be interpreted as flags to the 268allocation functions. 269.El 270.Sh RETURN VALUES 271The 272.Fn malloc 273and 274.Fn calloc 275functions return a pointer to the allocated memory if successful; otherwise 276a NULL pointer is returned. 277.Pp 278The 279.Fn realloc 280.\"XXX"and 281.\"XXX".Fn reallocf 282.\"XXX"functions return 283function returns 284a pointer, possibly identical to 285.Fa ptr , 286to the allocated memory 287if successful; otherwise a NULL pointer is returned, in which case the 288memory referenced by 289.Fa ptr 290is still available and intact. 291.Pp 292The 293.Fn free 294function returns no value. 295.Sh "DEBUGGING MALLOC PROBLEMS" 296.Pp 297The major difference between this implementation and other allocation 298implementations is that the free pages are not accessed unless allocated, 299and are aggressively returned to the kernel for reuse. 300.Bd -filled -offset indent 301Most allocation implementations will store a data structure containing a 302linked list in the free chunks of memory, 303used to tie all the free memory together. 304That can be suboptimal, 305as every time the free-list is traversed, 306the otherwise unused, and likely paged out, 307pages are faulted into primary memory. 308On systems which are paging, 309this can result in a factor of five increase in the number of page-faults 310done by a process. 311.Ed 312.Pp 313A side effect of this architecture is that many minor transgressions on 314the interface which would traditionally not be detected are in fact 315detected. As a result, programs that have been running happily for 316years may suddenly start to complain loudly, when linked with this 317allocation implementation. 318.Pp 319The first and most important thing to do is to set the 320.Dq A 321option. 322This option forces a coredump (if possible) at the first sign of trouble, 323rather than the normal policy of trying to continue if at all possible. 324.Pp 325It is probably also a good idea to recompile the program with suitable 326options and symbols for debugger support. 327.Pp 328If the program starts to give unusual results, coredump or generally behave 329differently without emitting any of the messages listed in the next 330section, it is likely because it depends on the storage being filled with 331nul bytes. Try running it with 332.Dq Z 333option set; 334if that improves the situation, this diagnosis has been confirmed. 335If the program still misbehaves, 336the likely problem is accessing memory outside the allocated area, 337more likely after than before the allocated area. 338.Pp 339Alternatively, if the symptoms are not easy to reproduce, setting the 340.Dq J 341option may help provoke the problem. 342.Pp 343In truly difficult cases, the 344.Dq U 345option, if supported by the kernel, can provide a detailed trace of 346all calls made to these functions. 347.Pp 348Unfortunately this implementation does not provide much detail about 349the problems it detects, the performance impact for storing such information 350would be prohibitive. 351There are a number of allocation implementations available on the 'Net 352which focus on detecting and pinpointing problems by trading performance 353for extra sanity checks and detailed diagnostics. 354.Sh "DIAGNOSTIC MESSAGES 355If 356.Fn malloc , 357.Fn calloc , 358.Fn realloc 359or 360.Fn free 361detect an error or warning condition, 362a message will be printed to file descriptor STDERR_FILENO. 363Errors will result in the process dumping core. 364If the 365.Dq A 366option is set, all warnings are treated as errors. 367.Pp 368The following is a brief description of possible error messages and 369their meanings: 370.Pp 371.Bl -tag -width indent 372.It "(ES): mumble mumble mumble 373The allocation functions were compiled with 374.Dq EXTRA_SANITY 375defined, and an error was found during the additional error checking. 376Consult the source code for further information. 377.It "allocation failed 378If the 379.Dq A 380option is specified it is a fatal error for an allocation function to fail. 381.It "mmap(2) failed, check limits 382This most likely means that the system is dangerously overloaded or that 383the process' limits are incorrectly specified. 384.It "freelist is destroyed 385The internal free-list has been corrupted. 386.El 387.Pp 388.Bl -tag -width indent 389The following is a brief description of possible warning messages and 390their meanings: 391.Pp 392.It "chunk/page is already free 393The process attempted to 394.Fn free 395memory which had already been freed. 396.It "junk pointer ... 397A pointer specified to one of the allocation functions points outside the 398bounds of the memory of which they are aware. 399.It "malloc() has never been called 400No memory has been allocated, 401yet something is being freed or 402realloc'ed. 403.It "modified (chunk-/page-) pointer 404The pointer passed to 405.Fn free 406or 407.Fn realloc 408has been modified. 409.It "pointer to wrong page 410The pointer that 411.Fn malloc 412or 413.Fn calloc 414is trying to free does not reference a possible page. 415.It "recursive call 416A process has attempted to call an allocation function recursively. 417This is not permitted. In particular, signal handlers should not 418attempt to allocate memory. 419.It "out of memory 420The 421.Dq X 422option was specified and an allocation of memory failed. 423.It "unknown char in MALLOC_OPTIONS 424An unknown option was specified. 425Even with the 426.Dq A 427option set, this warning is still only a warning. 428.El 429.Sh SEE ALSO 430.Xr brk 2 , 431.Xr alloca 3 , 432.Xr getpagesize 3 , 433.Xr memory 3 434.\"XXX" .Pa /usr/share/doc/papers/malloc.ascii.gz 435.Sh STANDARDS 436The 437.Fn malloc , 438.Fn calloc , 439.Fn realloc 440and 441.Fn free 442functions conform to 443.St -ansiC . 444.Sh BUGS 445The messages printed in case of problems provide no detail about the 446actual values. 447.Pp 448It can be argued that returning a null pointer when asked to 449allocate zero bytes is a silly response to a silly question. 450.Pp 451This implementation was authored by Poul-Henning Kamp. 452Please report any problems to him at 453.Li <phk@FreeBSD.org> . 454.Sh HISTORY 455The present allocation implementation started out as a filesystem for a 456drum attached to a 20bit binary challenged computer which was built 457with discrete germanium transistors. It has since graduated to 458handle primary storage rather than secondary. 459It first appeared in its new shape and ability in 460.Fx 2.2 , and then in 461.Nx 1.5 . 462