(linenum→info "unix/slp.c:2238")

glibc/2.7/manual/memory.texi

    1: @node Memory, Character Handling, Error Reporting, Top
    2: @chapter Virtual Memory Allocation And Paging
    3: @c %MENU% Allocating virtual memory and controlling paging
    4: @cindex memory allocation
    5: @cindex storage allocation
    6: 
    7: This chapter describes how processes manage and use memory in a system
    8: that uses the GNU C library.
    9: 
   10: The GNU C Library has several functions for dynamically allocating
   11: virtual memory in various ways.  They vary in generality and in
   12: efficiency.  The library also provides functions for controlling paging
   13: and allocation of real memory.
   14: 
   15: 
   16: @menu
   17: * Memory Concepts::             An introduction to concepts and terminology.
   18: * Memory Allocation::           Allocating storage for your program data
   19: * Locking Pages::               Preventing page faults
   20: * Resizing the Data Segment::   @code{brk}, @code{sbrk}
   21: @end menu
   22: 
   23: Memory mapped I/O is not discussed in this chapter.  @xref{Memory-mapped I/O}.
   24: 
   25: 
   26: 
   27: @node Memory Concepts
   28: @section Process Memory Concepts
   29: 
   30: One of the most basic resources a process has available to it is memory.
   31: There are a lot of different ways systems organize memory, but in a
   32: typical one, each process has one linear virtual address space, with
   33: addresses running from zero to some huge maximum.  It need not be
   34: contiguous; i.e., not all of these addresses actually can be used to
   35: store data.
   36: 
   37: The virtual memory is divided into pages (4 kilobytes is typical).
   38: Backing each page of virtual memory is a page of real memory (called a
   39: @dfn{frame}) or some secondary storage, usually disk space.  The disk
   40: space might be swap space or just some ordinary disk file.  Actually, a
   41: page of all zeroes sometimes has nothing at all backing it -- there's
   42: just a flag saying it is all zeroes.
   43: @cindex page frame
   44: @cindex frame, real memory
   45: @cindex swap space
   46: @cindex page, virtual memory
   47: 
   48: The same frame of real memory or backing store can back multiple virtual
   49: pages belonging to multiple processes.  This is normally the case, for
   50: example, with virtual memory occupied by GNU C library code.  The same
   51: real memory frame containing the @code{printf} function backs a virtual
   52: memory page in each of the existing processes that has a @code{printf}
   53: call in its program.
   54: 
   55: In order for a program to access any part of a virtual page, the page
   56: must at that moment be backed by (``connected to'') a real frame.  But
   57: because there is usually a lot more virtual memory than real memory, the
   58: pages must move back and forth between real memory and backing store
   59: regularly, coming into real memory when a process needs to access them
   60: and then retreating to backing store when not needed anymore.  This
   61: movement is called @dfn{paging}.
   62: 
   63: When a program attempts to access a page which is not at that moment
   64: backed by real memory, this is known as a @dfn{page fault}.  When a page
   65: fault occurs, the kernel suspends the process, places the page into a
   66: real page frame (this is called ``paging in'' or ``faulting in''), then
   67: resumes the process so that from the process' point of view, the page
   68: was in real memory all along.  In fact, to the process, all pages always
   69: seem to be in real memory.  Except for one thing: the elapsed execution
   70: time of an instruction that would normally be a few nanoseconds is
   71: suddenly much, much, longer (because the kernel normally has to do I/O
   72: to complete the page-in).  For programs sensitive to that, the functions
   73: described in @ref{Locking Pages} can control it.
   74: @cindex page fault
   75: @cindex paging
   76: 
   77: Within each virtual address space, a process has to keep track of what
   78: is at which addresses, and that process is called memory allocation.
   79: Allocation usually brings to mind meting out scarce resources, but in
   80: the case of virtual memory, that's not a major goal, because there is
   81: generally much more of it than anyone needs.  Memory allocation within a
   82: process is mainly just a matter of making sure that the same byte of
   83: memory isn't used to store two different things.
   84: 
   85: Processes allocate memory in two major ways: by exec and
   86: programmatically.  Actually, forking is a third way, but it's not very
   87: interesting.  @xref{Creating a Process}.
   88: 
   89: Exec is the operation of creating a virtual address space for a process,
   90: loading its basic program into it, and executing the program.  It is
   91: done by the ``exec'' family of functions (e.g. @code{execl}).  The
   92: operation takes a program file (an executable), it allocates space to
   93: load all the data in the executable, loads it, and transfers control to
   94: it.  That data is most notably the instructions of the program (the
   95: @dfn{text}), but also literals and constants in the program and even
   96: some variables: C variables with the static storage class (@pxref{Memory
   97: Allocation and C}).
   98: @cindex executable
   99: @cindex literals
  100: @cindex constants
  101: 
  102: Once that program begins to execute, it uses programmatic allocation to
  103: gain additional memory.  In a C program with the GNU C library, there
  104: are two kinds of programmatic allocation: automatic and dynamic.
  105: @xref{Memory Allocation and C}.
  106: 
  107: Memory-mapped I/O is another form of dynamic virtual memory allocation.
  108: Mapping memory to a file means declaring that the contents of certain
  109: range of a process' addresses shall be identical to the contents of a
  110: specified regular file.  The system makes the virtual memory initially
  111: contain the contents of the file, and if you modify the memory, the
  112: system writes the same modification to the file.  Note that due to the
  113: magic of virtual memory and page faults, there is no reason for the
  114: system to do I/O to read the file, or allocate real memory for its
  115: contents, until the program accesses the virtual memory.
  116: @xref{Memory-mapped I/O}.
  117: @cindex memory mapped I/O
  118: @cindex memory mapped file
  119: @cindex files, accessing
  120: 
  121: Just as it programmatically allocates memory, the program can
  122: programmatically deallocate (@dfn{free}) it.  You can't free the memory
  123: that was allocated by exec.  When the program exits or execs, you might
  124: say that all its memory gets freed, but since in both cases the address
  125: space ceases to exist, the point is really moot.  @xref{Program
  126: Termination}.
  127: @cindex execing a program
  128: @cindex freeing memory
  129: @cindex exiting a program
  130: 
  131: A process' virtual address space is divided into segments.  A segment is
  132: a contiguous range of virtual addresses.  Three important segments are:
  133: 
  134: @itemize @bullet
  135: 
  136: @item
  137: 
  138: The @dfn{text segment} contains a program's instructions and literals and
  139: static constants.  It is allocated by exec and stays the same size for
  140: the life of the virtual address space.
  141: 
  142: @item
  143: The @dfn{data segment} is working storage for the program.  It can be
  144: preallocated and preloaded by exec and the process can extend or shrink
  145: it by calling functions as described in @xref{Resizing the Data
  146: Segment}.  Its lower end is fixed.
  147: 
  148: @item
  149: The @dfn{stack segment} contains a program stack.  It grows as the stack
  150: grows, but doesn't shrink when the stack shrinks.
  151: 
  152: @end itemize
  153: 
  154: 
  155: 
  156: @node Memory Allocation
  157: @section Allocating Storage For Program Data
  158: 
  159: This section covers how ordinary programs manage storage for their data,
  160: including the famous @code{malloc} function and some fancier facilities
  161: special the GNU C library and GNU Compiler.
  162: 
  163: @menu
  164: * Memory Allocation and C::     How to get different kinds of allocation in C.
  165: * Unconstrained Allocation::    The @code{malloc} facility allows fully general
  166:                                dynamic allocation.
  167: * Allocation Debugging::        Finding memory leaks and not freed memory.
  168: * Obstacks::                    Obstacks are less general than malloc
  169:                                  but more efficient and convenient.
  170: * Variable Size Automatic::     Allocation of variable-sized blocks
  171:                                  of automatic storage that are freed when the
  172:                                  calling function returns.
  173: @end menu
  174: 
  175: 
  176: @node Memory Allocation and C
  177: @subsection Memory Allocation in C Programs
  178: 
  179: The C language supports two kinds of memory allocation through the
  180: variables in C programs:
  181: 
  182: @itemize @bullet
  183: @item
  184: @dfn{Static allocation} is what happens when you declare a static or
  185: global variable.  Each static or global variable defines one block of
  186: space, of a fixed size.  The space is allocated once, when your program
  187: is started (part of the exec operation), and is never freed.
  188: @cindex static memory allocation
  189: @cindex static storage class
  190: 
  191: @item
  192: @dfn{Automatic allocation} happens when you declare an automatic
  193: variable, such as a function argument or a local variable.  The space
  194: for an automatic variable is allocated when the compound statement
  195: containing the declaration is entered, and is freed when that
  196: compound statement is exited.
  197: @cindex automatic memory allocation
  198: @cindex automatic storage class
  199: 
  200: In GNU C, the size of the automatic storage can be an expression
  201: that varies.  In other C implementations, it must be a constant.
  202: @end itemize
  203: 
  204: A third important kind of memory allocation, @dfn{dynamic allocation},
  205: is not supported by C variables but is available via GNU C library
  206: functions.
  207: @cindex dynamic memory allocation
  208: 
  209: @subsubsection Dynamic Memory Allocation
  210: @cindex dynamic memory allocation
  211: 
  212: @dfn{Dynamic memory allocation} is a technique in which programs
  213: determine as they are running where to store some information.  You need
  214: dynamic allocation when the amount of memory you need, or how long you
  215: continue to need it, depends on factors that are not known before the
  216: program runs.
  217: 
  218: For example, you may need a block to store a line read from an input
  219: file; since there is no limit to how long a line can be, you must
  220: allocate the memory dynamically and make it dynamically larger as you
  221: read more of the line.
  222: 
  223: Or, you may need a block for each record or each definition in the input
  224: data; since you can't know in advance how many there will be, you must
  225: allocate a new block for each record or definition as you read it.
  226: 
  227: When you use dynamic allocation, the allocation of a block of memory is
  228: an action that the program requests explicitly.  You call a function or
  229: macro when you want to allocate space, and specify the size with an
  230: argument.  If you want to free the space, you do so by calling another
  231: function or macro.  You can do these things whenever you want, as often
  232: as you want.
  233: 
  234: Dynamic allocation is not supported by C variables; there is no storage
  235: class ``dynamic'', and there can never be a C variable whose value is
  236: stored in dynamically allocated space.  The only way to get dynamically
  237: allocated memory is via a system call (which is generally via a GNU C
  238: library function call), and the only way to refer to dynamically
  239: allocated space is through a pointer.  Because it is less convenient,
  240: and because the actual process of dynamic allocation requires more
  241: computation time, programmers generally use dynamic allocation only when
  242: neither static nor automatic allocation will serve.
  243: 
  244: For example, if you want to allocate dynamically some space to hold a
  245: @code{struct foobar}, you cannot declare a variable of type @code{struct
  246: foobar} whose contents are the dynamically allocated space.  But you can
  247: declare a variable of pointer type @code{struct foobar *} and assign it the
  248: address of the space.  Then you can use the operators @samp{*} and
  249: @samp{->} on this pointer variable to refer to the contents of the space:
  250: 
  251: @smallexample
  252: @{
  253:   struct foobar *ptr
  254:      = (struct foobar *) malloc (sizeof (struct foobar));
  255:   ptr->name = x;
  256:   ptr->next = current_foobar;
  257:   current_foobar = ptr;
  258: @}
  259: @end smallexample
  260: 
  261: @node Unconstrained Allocation
  262: @subsection Unconstrained Allocation
  263: @cindex unconstrained memory allocation
  264: @cindex @code{malloc} function
  265: @cindex heap, dynamic allocation from
  266: 
  267: The most general dynamic allocation facility is @code{malloc}.  It
  268: allows you to allocate blocks of memory of any size at any time, make
  269: them bigger or smaller at any time, and free the blocks individually at
  270: any time (or never).
  271: 
  272: @menu
  273: * Basic Allocation::            Simple use of @code{malloc}.
  274: * Malloc Examples::             Examples of @code{malloc}.  @code{xmalloc}.
  275: * Freeing after Malloc::        Use @code{free} to free a block you
  276:                                  got with @code{malloc}.
  277: * Changing Block Size::         Use @code{realloc} to make a block
  278:                                  bigger or smaller.
  279: * Allocating Cleared Space::    Use @code{calloc} to allocate a
  280:                                  block and clear it.
  281: * Efficiency and Malloc::       Efficiency considerations in use of
  282:                                  these functions.
  283: * Aligned Memory Blocks::       Allocating specially aligned memory.
  284: * Malloc Tunable Parameters::   Use @code{mallopt} to adjust allocation
  285:                                  parameters.
  286: * Heap Consistency Checking::   Automatic checking for errors.
  287: * Hooks for Malloc::            You can use these hooks for debugging
  288:                                  programs that use @code{malloc}.
  289: * Statistics of Malloc::        Getting information about how much
  290:                                  memory your program is using.
  291: * Summary of Malloc::           Summary of @code{malloc} and related functions.
  292: @end menu
  293: 
  294: @node Basic Allocation
  295: @subsubsection Basic Memory Allocation
  296: @cindex allocation of memory with @code{malloc}
  297: 
  298: To allocate a block of memory, call @code{malloc}.  The prototype for
  299: this function is in @file{stdlib.h}.
  300: @pindex stdlib.h
  301: 
  302: @comment malloc.h stdlib.h
  303: @comment ISO
  304: @deftypefun {void *} malloc (size_t @var{size})
  305: This function returns a pointer to a newly allocated block @var{size}
  306: bytes long, or a null pointer if the block could not be allocated.
  307: @end deftypefun
  308: 
  309: The contents of the block are undefined; you must initialize it yourself
  310: (or use @code{calloc} instead; @pxref{Allocating Cleared Space}).
  311: Normally you would cast the value as a pointer to the kind of object
  312: that you want to store in the block.  Here we show an example of doing
  313: so, and of initializing the space with zeros using the library function
  314: @code{memset} (@pxref{Copying and Concatenation}):
  315: 
  316: @smallexample
  317: struct foo *ptr;
  318: @dots{}
  319: ptr = (struct foo *) malloc (sizeof (struct foo));
  320: if (ptr == 0) abort ();
  321: memset (ptr, 0, sizeof (struct foo));
  322: @end smallexample
  323: 
  324: You can store the result of @code{malloc} into any pointer variable
  325: without a cast, because @w{ISO C} automatically converts the type
  326: @code{void *} to another type of pointer when necessary.  But the cast
  327: is necessary in contexts other than assignment operators or if you might
  328: want your code to run in traditional C.
  329: 
  330: Remember that when allocating space for a string, the argument to
  331: @code{malloc} must be one plus the length of the string.  This is
  332: because a string is terminated with a null character that doesn't count
  333: in the ``length'' of the string but does need space.  For example:
  334: 
  335: @smallexample
  336: char *ptr;
  337: @dots{}
  338: ptr = (char *) malloc (length + 1);
  339: @end smallexample
  340: 
  341: @noindent
  342: @xref{Representation of Strings}, for more information about this.
  343: 
  344: @node Malloc Examples
  345: @subsubsection Examples of @code{malloc}
  346: 
  347: If no more space is available, @code{malloc} returns a null pointer.
  348: You should check the value of @emph{every} call to @code{malloc}.  It is
  349: useful to write a subroutine that calls @code{malloc} and reports an
  350: error if the value is a null pointer, returning only if the value is
  351: nonzero.  This function is conventionally called @code{xmalloc}.  Here
  352: it is:
  353: 
  354: @smallexample
  355: void *
  356: xmalloc (size_t size)
  357: @{
  358:   register void *value = malloc (size);
  359:   if (value == 0)
  360:     fatal ("virtual memory exhausted");
  361:   return value;
  362: @}
  363: @end smallexample
  364: 
  365: Here is a real example of using @code{malloc} (by way of @code{xmalloc}).
  366: The function @code{savestring} will copy a sequence of characters into
  367: a newly allocated null-terminated string:
  368: 
  369: @smallexample
  370: @group
  371: char *
  372: savestring (const char *ptr, size_t len)
  373: @{
  374:   register char *value = (char *) xmalloc (len + 1);
  375:   value[len] = '\0';
  376:   return (char *) memcpy (value, ptr, len);
  377: @}
  378: @end group
  379: @end smallexample
  380: 
  381: The block that @code{malloc} gives you is guaranteed to be aligned so
  382: that it can hold any type of data.  In the GNU system, the address is
  383: always a multiple of eight on most systems, and a multiple of 16 on
  384: 64-bit systems.  Only rarely is any higher boundary (such as a page
  385: boundary) necessary; for those cases, use @code{memalign},
  386: @code{posix_memalign} or @code{valloc} (@pxref{Aligned Memory Blocks}).
  387: 
  388: Note that the memory located after the end of the block is likely to be
  389: in use for something else; perhaps a block already allocated by another
  390: call to @code{malloc}.  If you attempt to treat the block as longer than
  391: you asked for it to be, you are liable to destroy the data that
  392: @code{malloc} uses to keep track of its blocks, or you may destroy the
  393: contents of another block.  If you have already allocated a block and
  394: discover you want it to be bigger, use @code{realloc} (@pxref{Changing
  395: Block Size}).
  396: 
  397: @node Freeing after Malloc
  398: @subsubsection Freeing Memory Allocated with @code{malloc}
  399: @cindex freeing memory allocated with @code{malloc}
  400: @cindex heap, freeing memory from
  401: 
  402: When you no longer need a block that you got with @code{malloc}, use the
  403: function @code{free} to make the block available to be allocated again.
  404: The prototype for this function is in @file{stdlib.h}.
  405: @pindex stdlib.h
  406: 
  407: @comment malloc.h stdlib.h
  408: @comment ISO
  409: @deftypefun void free (void *@var{ptr})
  410: The @code{free} function deallocates the block of memory pointed at
  411: by @var{ptr}.
  412: @end deftypefun
  413: 
  414: @comment stdlib.h
  415: @comment Sun
  416: @deftypefun void cfree (void *@var{ptr})
  417: This function does the same thing as @code{free}.  It's provided for
  418: backward compatibility with SunOS; you should use @code{free} instead.
  419: @end deftypefun
  420: 
  421: Freeing a block alters the contents of the block.  @strong{Do not expect to
  422: find any data (such as a pointer to the next block in a chain of blocks) in
  423: the block after freeing it.}  Copy whatever you need out of the block before
  424: freeing it!  Here is an example of the proper way to free all the blocks in
  425: a chain, and the strings that they point to:
  426: 
  427: @smallexample
  428: struct chain
  429:   @{
  430:     struct chain *next;
  431:     char *name;
  432:   @}
  433: 
  434: void
  435: free_chain (struct chain *chain)
  436: @{
  437:   while (chain != 0)
  438:     @{
  439:       struct chain *next = chain->next;
  440:       free (chain->name);
  441:       free (chain);
  442:       chain = next;
  443:     @}
  444: @}
  445: @end smallexample
  446: 
  447: Occasionally, @code{free} can actually return memory to the operating
  448: system and make the process smaller.  Usually, all it can do is allow a
  449: later call to @code{malloc} to reuse the space.  In the meantime, the
  450: space remains in your program as part of a free-list used internally by
  451: @code{malloc}.
  452: 
  453: There is no point in freeing blocks at the end of a program, because all
  454: of the program's space is given back to the system when the process
  455: terminates.
  456: 
  457: @node Changing Block Size
  458: @subsubsection Changing the Size of a Block
  459: @cindex changing the size of a block (@code{malloc})
  460: 
  461: Often you do not know for certain how big a block you will ultimately need
  462: at the time you must begin to use the block.  For example, the block might
  463: be a buffer that you use to hold a line being read from a file; no matter
  464: how long you make the buffer initially, you may encounter a line that is
  465: longer.
  466: 
  467: You can make the block longer by calling @code{realloc}.  This function
  468: is declared in @file{stdlib.h}.
  469: @pindex stdlib.h
  470: 
  471: @comment malloc.h stdlib.h
  472: @comment ISO
  473: @deftypefun {void *} realloc (void *@var{ptr}, size_t @var{newsize})
  474: The @code{realloc} function changes the size of the block whose address is
  475: @var{ptr} to be @var{newsize}.
  476: 
  477: Since the space after the end of the block may be in use, @code{realloc}
  478: may find it necessary to copy the block to a new address where more free
  479: space is available.  The value of @code{realloc} is the new address of the
  480: block.  If the block needs to be moved, @code{realloc} copies the old
  481: contents.
  482: 
  483: If you pass a null pointer for @var{ptr}, @code{realloc} behaves just
  484: like @samp{malloc (@var{newsize})}.  This can be convenient, but beware
  485: that older implementations (before @w{ISO C}) may not support this
  486: behavior, and will probably crash when @code{realloc} is passed a null
  487: pointer.
  488: @end deftypefun
  489: 
  490: Like @code{malloc}, @code{realloc} may return a null pointer if no
  491: memory space is available to make the block bigger.  When this happens,
  492: the original block is untouched; it has not been modified or relocated.
  493: 
  494: In most cases it makes no difference what happens to the original block
  495: when @code{realloc} fails, because the application program cannot continue
  496: when it is out of memory, and the only thing to do is to give a fatal error
  497: message.  Often it is convenient to write and use a subroutine,
  498: conventionally called @code{xrealloc}, that takes care of the error message
  499: as @code{xmalloc} does for @code{malloc}:
  500: 
  501: @smallexample
  502: void *
  503: xrealloc (void *ptr, size_t size)
  504: @{
  505:   register void *value = realloc (ptr, size);
  506:   if (value == 0)
  507:     fatal ("Virtual memory exhausted");
  508:   return value;
  509: @}
  510: @end smallexample
  511: 
  512: You can also use @code{realloc} to make a block smaller.  The reason you
  513: would do this is to avoid tying up a lot of memory space when only a little
  514: is needed.
  515: @comment The following is no longer true with the new malloc.
  516: @comment But it seems wise to keep the warning for other implementations.
  517: In several allocation implementations, making a block smaller sometimes
  518: necessitates copying it, so it can fail if no other space is available.
  519: 
  520: If the new size you specify is the same as the old size, @code{realloc}
  521: is guaranteed to change nothing and return the same address that you gave.
  522: 
  523: @node Allocating Cleared Space
  524: @subsubsection Allocating Cleared Space
  525: 
  526: The function @code{calloc} allocates memory and clears it to zero.  It
  527: is declared in @file{stdlib.h}.
  528: @pindex stdlib.h
  529: 
  530: @comment malloc.h stdlib.h
  531: @comment ISO
  532: @deftypefun {void *} calloc (size_t @var{count}, size_t @var{eltsize})
  533: This function allocates a block long enough to contain a vector of
  534: @var{count} elements, each of size @var{eltsize}.  Its contents are
  535: cleared to zero before @code{calloc} returns.
  536: @end deftypefun
  537: 
  538: You could define @code{calloc} as follows:
  539: 
  540: @smallexample
  541: void *
  542: calloc (size_t count, size_t eltsize)
  543: @{
  544:   size_t size = count * eltsize;
  545:   void *value = malloc (size);
  546:   if (value != 0)
  547:     memset (value, 0, size);
  548:   return value;
  549: @}
  550: @end smallexample
  551: 
  552: But in general, it is not guaranteed that @code{calloc} calls
  553: @code{malloc} internally.  Therefore, if an application provides its own
  554: @code{malloc}/@code{realloc}/@code{free} outside the C library, it
  555: should always define @code{calloc}, too.
  556: 
  557: @node Efficiency and Malloc
  558: @subsubsection Efficiency Considerations for @code{malloc}
  559: @cindex efficiency and @code{malloc}
  560: 
  561: 
  562: 
  563: 
  564: @ignore
  565: 
  566: @c No longer true, see below instead.
  567: To make the best use of @code{malloc}, it helps to know that the GNU
  568: version of @code{malloc} always dispenses small amounts of memory in
  569: blocks whose sizes are powers of two.  It keeps separate pools for each
  570: power of two.  This holds for sizes up to a page size.  Therefore, if
  571: you are free to choose the size of a small block in order to make
  572: @code{malloc} more efficient, make it a power of two.
  573: @c !!! xref getpagesize
  574: 
  575: Once a page is split up for a particular block size, it can't be reused
  576: for another size unless all the blocks in it are freed.  In many
  577: programs, this is unlikely to happen.  Thus, you can sometimes make a
  578: program use memory more efficiently by using blocks of the same size for
  579: many different purposes.
  580: 
  581: When you ask for memory blocks of a page or larger, @code{malloc} uses a
  582: different strategy; it rounds the size up to a multiple of a page, and
  583: it can coalesce and split blocks as needed.
  584: 
  585: The reason for the two strategies is that it is important to allocate
  586: and free small blocks as fast as possible, but speed is less important
  587: for a large block since the program normally spends a fair amount of
  588: time using it.  Also, large blocks are normally fewer in number.
  589: Therefore, for large blocks, it makes sense to use a method which takes
  590: more time to minimize the wasted space.
  591: 
  592: @end ignore
  593: 
  594: As opposed to other versions, the @code{malloc} in the GNU C Library
  595: does not round up block sizes to powers of two, neither for large nor
  596: for small sizes.  Neighboring chunks can be coalesced on a @code{free}
  597: no matter what their size is.  This makes the implementation suitable
  598: for all kinds of allocation patterns without generally incurring high
  599: memory waste through fragmentation.
  600: 
  601: Very large blocks (much larger than a page) are allocated with
  602: @code{mmap} (anonymous or via @code{/dev/zero}) by this implementation.
  603: This has the great advantage that these chunks are returned to the
  604: system immediately when they are freed.  Therefore, it cannot happen
  605: that a large chunk becomes ``locked'' in between smaller ones and even
  606: after calling @code{free} wastes memory.  The size threshold for
  607: @code{mmap} to be used can be adjusted with @code{mallopt}.  The use of
  608: @code{mmap} can also be disabled completely.
  609: 
  610: @node Aligned Memory Blocks
  611: @subsubsection Allocating Aligned Memory Blocks
  612: 
  613: @cindex page boundary
  614: @cindex alignment (with @code{malloc})
  615: @pindex stdlib.h
  616: The address of a block returned by @code{malloc} or @code{realloc} in
  617: the GNU system is always a multiple of eight (or sixteen on 64-bit
  618: systems).  If you need a block whose address is a multiple of a higher
  619: power of two than that, use @code{memalign}, @code{posix_memalign}, or
  620: @code{valloc}.  @code{memalign} is declared in @file{malloc.h} and
  621: @code{posix_memalign} is declared in @file{stdlib.h}.
  622: 
  623: With the GNU library, you can use @code{free} to free the blocks that
  624: @code{memalign}, @code{posix_memalign}, and @code{valloc} return.  That
  625: does not work in BSD, however---BSD does not provide any way to free
  626: such blocks.
  627: 
  628: @comment malloc.h
  629: @comment BSD
  630: @deftypefun {void *} memalign (size_t @var{boundary}, size_t @var{size})
  631: The @code{memalign} function allocates a block of @var{size} bytes whose
  632: address is a multiple of @var{boundary}.  The @var{boundary} must be a
  633: power of two!  The function @code{memalign} works by allocating a
  634: somewhat larger block, and then returning an address within the block
  635: that is on the specified boundary.
  636: @end deftypefun
  637: 
  638: @comment stdlib.h
  639: @comment POSIX
  640: @deftypefun int posix_memalign (void **@var{memptr}, size_t @var{alignment}, size_t @var{size})
  641: The @code{posix_memalign} function is similar to the @code{memalign}
  642: function in that it returns a buffer of @var{size} bytes aligned to a
  643: multiple of @var{alignment}.  But it adds one requirement to the
  644: parameter @var{alignment}: the value must be a power of two multiple of
  645: @code{sizeof (void *)}.
  646: 
  647: If the function succeeds in allocation memory a pointer to the allocated
  648: memory is returned in @code{*@var{memptr}} and the return value is zero.
  649: Otherwise the function returns an error value indicating the problem.
  650: 
  651: This function was introduced in POSIX 1003.1d.
  652: @end deftypefun
  653: 
  654: @comment malloc.h stdlib.h
  655: @comment BSD
  656: @deftypefun {void *} valloc (size_t @var{size})
  657: Using @code{valloc} is like using @code{memalign} and passing the page size
  658: as the value of the second argument.  It is implemented like this:
  659: 
  660: @smallexample
  661: void *
  662: valloc (size_t size)
  663: @{
  664:   return memalign (getpagesize (), size);
  665: @}
  666: @end smallexample
  667: 
  668: @ref{Query Memory Parameters} for more information about the memory
  669: subsystem.
  670: @end deftypefun
  671: 
  672: @node Malloc Tunable Parameters
  673: @subsubsection Malloc Tunable Parameters
  674: 
  675: You can adjust some parameters for dynamic memory allocation with the
  676: @code{mallopt} function.  This function is the general SVID/XPG
  677: interface, defined in @file{malloc.h}.
  678: @pindex malloc.h
  679: 
  680: @deftypefun int mallopt (int @var{param}, int @var{value})
  681: When calling @code{mallopt}, the @var{param} argument specifies the
  682: parameter to be set, and @var{value} the new value to be set.  Possible
  683: choices for @var{param}, as defined in @file{malloc.h}, are:
  684: 
  685: @table @code
  686: @item M_TRIM_THRESHOLD
  687: This is the minimum size (in bytes) of the top-most, releasable chunk
  688: that will cause @code{sbrk} to be called with a negative argument in
  689: order to return memory to the system.
  690: @item M_TOP_PAD
  691: This parameter determines the amount of extra memory to obtain from the
  692: system when a call to @code{sbrk} is required.  It also specifies the
  693: number of bytes to retain when shrinking the heap by calling @code{sbrk}
  694: with a negative argument.  This provides the necessary hysteresis in
  695: heap size such that excessive amounts of system calls can be avoided.
  696: @item M_MMAP_THRESHOLD
  697: All chunks larger than this value are allocated outside the normal
  698: heap, using the @code{mmap} system call.  This way it is guaranteed
  699: that the memory for these chunks can be returned to the system on
  700: @code{free}.  Note that requests smaller than this threshold might still
  701: be allocated via @code{mmap}.
  702: @item M_MMAP_MAX
  703: The maximum number of chunks to allocate with @code{mmap}.  Setting this
  704: to zero disables all use of @code{mmap}.
  705: @end table
  706: 
  707: @end deftypefun
  708: 
  709: @node Heap Consistency Checking
  710: @subsubsection Heap Consistency Checking
  711: 
  712: @cindex heap consistency checking
  713: @cindex consistency checking, of heap
  714: 
  715: You can ask @code{malloc} to check the consistency of dynamic memory by
  716: using the @code{mcheck} function.  This function is a GNU extension,
  717: declared in @file{mcheck.h}.
  718: @pindex mcheck.h
  719: 
  720: @comment mcheck.h
  721: @comment GNU
  722: @deftypefun int mcheck (void (*@var{abortfn}) (enum mcheck_status @var{status}))
  723: Calling @code{mcheck} tells @code{malloc} to perform occasional
  724: consistency checks.  These will catch things such as writing
  725: past the end of a block that was allocated with @code{malloc}.
  726: 
  727: The @var{abortfn} argument is the function to call when an inconsistency
  728: is found.  If you supply a null pointer, then @code{mcheck} uses a
  729: default function which prints a message and calls @code{abort}
  730: (@pxref{Aborting a Program}).  The function you supply is called with
  731: one argument, which says what sort of inconsistency was detected; its
  732: type is described below.
  733: 
  734: It is too late to begin allocation checking once you have allocated
  735: anything with @code{malloc}.  So @code{mcheck} does nothing in that
  736: case.  The function returns @code{-1} if you call it too late, and
  737: @code{0} otherwise (when it is successful).
  738: 
  739: The easiest way to arrange to call @code{mcheck} early enough is to use
  740: the option @samp{-lmcheck} when you link your program; then you don't
  741: need to modify your program source at all.  Alternatively you might use
  742: a debugger to insert a call to @code{mcheck} whenever the program is
  743: started, for example these gdb commands will automatically call @code{mcheck}
  744: whenever the program starts:
  745: 
  746: @smallexample
  747: (gdb) break main