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