Update.
[glibc.git] / manual / memory.texi
blobb87bc3f160937f55f1a0bf71f63689585096d3b5
1 @comment !!! describe mmap et al (here?)
2 @c !!! doc brk/sbrk
4 @node Memory Allocation, Character Handling, Error Reporting, Top
5 @chapter Memory Allocation
6 @c %MENU% Allocating memory dynamically and manipulating it via pointers
7 @cindex memory allocation
8 @cindex storage allocation
10 The GNU system provides several methods for allocating memory space
11 under explicit program control.  They vary in generality and in
12 efficiency.
14 @iftex
15 @itemize @bullet
16 @item
17 The @code{malloc} facility allows fully general dynamic allocation.
18 @xref{Unconstrained Allocation}.
20 @item
21 Obstacks are another facility, less general than @code{malloc} but more
22 efficient and convenient for stacklike allocation.  @xref{Obstacks}.
24 @item
25 The function @code{alloca} lets you allocate storage dynamically that
26 will be freed automatically.  @xref{Variable Size Automatic}.
27 @end itemize
28 @end iftex
30 @menu
31 * Memory Concepts::             An introduction to concepts and terminology.
32 * Dynamic Allocation and C::    How to get different kinds of allocation in C.
33 * Unconstrained Allocation::    The @code{malloc} facility allows fully general
34                                  dynamic allocation.
35 * Allocation Debugging::        Finding memory leaks and not freed memory.
36 * Obstacks::                    Obstacks are less general than malloc
37                                  but more efficient and convenient.
38 * Variable Size Automatic::     Allocation of variable-sized blocks
39                                  of automatic storage that are freed when the
40                                  calling function returns.
41 * Relocating Allocator::        Waste less memory, if you can tolerate
42                                  automatic relocation of the blocks you get.
43 @end menu
45 @node Memory Concepts
46 @section Dynamic Memory Allocation Concepts
47 @cindex dynamic allocation
48 @cindex static allocation
49 @cindex automatic allocation
51 @dfn{Dynamic memory allocation} is a technique in which programs
52 determine as they are running where to store some information.  You need
53 dynamic allocation when the number of memory blocks you need, or how
54 long you continue to need them, depends on the data you are working on.
56 For example, you may need a block to store a line read from an input file;
57 since there is no limit to how long a line can be, you must allocate the
58 storage dynamically and make it dynamically larger as you read more of the
59 line.
61 Or, you may need a block for each record or each definition in the input
62 data; since you can't know in advance how many there will be, you must
63 allocate a new block for each record or definition as you read it.
65 When you use dynamic allocation, the allocation of a block of memory is an
66 action that the program requests explicitly.  You call a function or macro
67 when you want to allocate space, and specify the size with an argument.  If
68 you want to free the space, you do so by calling another function or macro.
69 You can do these things whenever you want, as often as you want.
71 @node Dynamic Allocation and C
72 @section Dynamic Allocation and C
74 The C language supports two kinds of memory allocation through the variables
75 in C programs:
77 @itemize @bullet
78 @item
79 @dfn{Static allocation} is what happens when you declare a static or
80 global variable.  Each static or global variable defines one block of
81 space, of a fixed size.  The space is allocated once, when your program
82 is started, and is never freed.
84 @item
85 @dfn{Automatic allocation} happens when you declare an automatic
86 variable, such as a function argument or a local variable.  The space
87 for an automatic variable is allocated when the compound statement
88 containing the declaration is entered, and is freed when that
89 compound statement is exited.
91 In GNU C, the length of the automatic storage can be an expression
92 that varies.  In other C implementations, it must be a constant.
93 @end itemize
95 Dynamic allocation is not supported by C variables; there is no storage
96 class ``dynamic'', and there can never be a C variable whose value is
97 stored in dynamically allocated space.  The only way to refer to
98 dynamically allocated space is through a pointer.  Because it is less
99 convenient, and because the actual process of dynamic allocation
100 requires more computation time, programmers generally use dynamic
101 allocation only when neither static nor automatic allocation will serve.
103 For example, if you want to allocate dynamically some space to hold a
104 @code{struct foobar}, you cannot declare a variable of type @code{struct
105 foobar} whose contents are the dynamically allocated space.  But you can
106 declare a variable of pointer type @code{struct foobar *} and assign it the
107 address of the space.  Then you can use the operators @samp{*} and
108 @samp{->} on this pointer variable to refer to the contents of the space:
110 @smallexample
112   struct foobar *ptr
113      = (struct foobar *) malloc (sizeof (struct foobar));
114   ptr->name = x;
115   ptr->next = current_foobar;
116   current_foobar = ptr;
118 @end smallexample
120 @node Unconstrained Allocation
121 @section Unconstrained Allocation
122 @cindex unconstrained storage allocation
123 @cindex @code{malloc} function
124 @cindex heap, dynamic allocation from
126 The most general dynamic allocation facility is @code{malloc}.  It
127 allows you to allocate blocks of memory of any size at any time, make
128 them bigger or smaller at any time, and free the blocks individually at
129 any time (or never).
131 @menu
132 * Basic Allocation::            Simple use of @code{malloc}.
133 * Malloc Examples::             Examples of @code{malloc}.  @code{xmalloc}.
134 * Freeing after Malloc::        Use @code{free} to free a block you
135                                  got with @code{malloc}.
136 * Changing Block Size::         Use @code{realloc} to make a block
137                                  bigger or smaller.
138 * Allocating Cleared Space::    Use @code{calloc} to allocate a
139                                  block and clear it.
140 * Efficiency and Malloc::       Efficiency considerations in use of
141                                  these functions.
142 * Aligned Memory Blocks::       Allocating specially aligned memory:
143                                  @code{memalign} and @code{valloc}.
144 * Malloc Tunable Parameters::   Use @code{mallopt} to adjust allocation
145                                  parameters.
146 * Heap Consistency Checking::   Automatic checking for errors.
147 * Hooks for Malloc::            You can use these hooks for debugging
148                                  programs that use @code{malloc}.
149 * Statistics of Malloc::        Getting information about how much
150                                  memory your program is using.
151 * Summary of Malloc::           Summary of @code{malloc} and related functions.
152 @end menu
154 @node Basic Allocation
155 @subsection Basic Storage Allocation
156 @cindex allocation of memory with @code{malloc}
158 To allocate a block of memory, call @code{malloc}.  The prototype for
159 this function is in @file{stdlib.h}.
160 @pindex stdlib.h
162 @comment malloc.h stdlib.h
163 @comment ISO
164 @deftypefun {void *} malloc (size_t @var{size})
165 This function returns a pointer to a newly allocated block @var{size}
166 bytes long, or a null pointer if the block could not be allocated.
167 @end deftypefun
169 The contents of the block are undefined; you must initialize it yourself
170 (or use @code{calloc} instead; @pxref{Allocating Cleared Space}).
171 Normally you would cast the value as a pointer to the kind of object
172 that you want to store in the block.  Here we show an example of doing
173 so, and of initializing the space with zeros using the library function
174 @code{memset} (@pxref{Copying and Concatenation}):
176 @smallexample
177 struct foo *ptr;
178 @dots{}
179 ptr = (struct foo *) malloc (sizeof (struct foo));
180 if (ptr == 0) abort ();
181 memset (ptr, 0, sizeof (struct foo));
182 @end smallexample
184 You can store the result of @code{malloc} into any pointer variable
185 without a cast, because @w{ISO C} automatically converts the type
186 @code{void *} to another type of pointer when necessary.  But the cast
187 is necessary in contexts other than assignment operators or if you might
188 want your code to run in traditional C.
190 Remember that when allocating space for a string, the argument to
191 @code{malloc} must be one plus the length of the string.  This is
192 because a string is terminated with a null character that doesn't count
193 in the ``length'' of the string but does need space.  For example:
195 @smallexample
196 char *ptr;
197 @dots{}
198 ptr = (char *) malloc (length + 1);
199 @end smallexample
201 @noindent
202 @xref{Representation of Strings}, for more information about this.
204 @node Malloc Examples
205 @subsection Examples of @code{malloc}
207 If no more space is available, @code{malloc} returns a null pointer.
208 You should check the value of @emph{every} call to @code{malloc}.  It is
209 useful to write a subroutine that calls @code{malloc} and reports an
210 error if the value is a null pointer, returning only if the value is
211 nonzero.  This function is conventionally called @code{xmalloc}.  Here
212 it is:
214 @smallexample
215 void *
216 xmalloc (size_t size)
218   register void *value = malloc (size);
219   if (value == 0)
220     fatal ("virtual memory exhausted");
221   return value;
223 @end smallexample
225 Here is a real example of using @code{malloc} (by way of @code{xmalloc}).
226 The function @code{savestring} will copy a sequence of characters into
227 a newly allocated null-terminated string:
229 @smallexample
230 @group
231 char *
232 savestring (const char *ptr, size_t len)
234   register char *value = (char *) xmalloc (len + 1);
235   memcpy (value, ptr, len);
236   value[len] = '\0';
237   return value;
239 @end group
240 @end smallexample
242 The block that @code{malloc} gives you is guaranteed to be aligned so
243 that it can hold any type of data.  In the GNU system, the address is
244 always a multiple of eight on most systems, and a multiple of 16 on
245 64-bit systems.  Only rarely is any higher boundary (such as a page
246 boundary) necessary; for those cases, use @code{memalign} or
247 @code{valloc} (@pxref{Aligned Memory Blocks}).
249 Note that the memory located after the end of the block is likely to be
250 in use for something else; perhaps a block already allocated by another
251 call to @code{malloc}.  If you attempt to treat the block as longer than
252 you asked for it to be, you are liable to destroy the data that
253 @code{malloc} uses to keep track of its blocks, or you may destroy the
254 contents of another block.  If you have already allocated a block and
255 discover you want it to be bigger, use @code{realloc} (@pxref{Changing
256 Block Size}).
258 @node Freeing after Malloc
259 @subsection Freeing Memory Allocated with @code{malloc}
260 @cindex freeing memory allocated with @code{malloc}
261 @cindex heap, freeing memory from
263 When you no longer need a block that you got with @code{malloc}, use the
264 function @code{free} to make the block available to be allocated again.
265 The prototype for this function is in @file{stdlib.h}.
266 @pindex stdlib.h
268 @comment malloc.h stdlib.h
269 @comment ISO
270 @deftypefun void free (void *@var{ptr})
271 The @code{free} function deallocates the block of storage pointed at
272 by @var{ptr}.
273 @end deftypefun
275 @comment stdlib.h
276 @comment Sun
277 @deftypefun void cfree (void *@var{ptr})
278 This function does the same thing as @code{free}.  It's provided for
279 backward compatibility with SunOS; you should use @code{free} instead.
280 @end deftypefun
282 Freeing a block alters the contents of the block.  @strong{Do not expect to
283 find any data (such as a pointer to the next block in a chain of blocks) in
284 the block after freeing it.}  Copy whatever you need out of the block before
285 freeing it!  Here is an example of the proper way to free all the blocks in
286 a chain, and the strings that they point to:
288 @smallexample
289 struct chain
290   @{
291     struct chain *next;
292     char *name;
293   @}
295 void
296 free_chain (struct chain *chain)
298   while (chain != 0)
299     @{
300       struct chain *next = chain->next;
301       free (chain->name);
302       free (chain);
303       chain = next;
304     @}
306 @end smallexample
308 Occasionally, @code{free} can actually return memory to the operating
309 system and make the process smaller.  Usually, all it can do is allow a
310 later call to @code{malloc} to reuse the space.  In the meantime, the
311 space remains in your program as part of a free-list used internally by
312 @code{malloc}.
314 There is no point in freeing blocks at the end of a program, because all
315 of the program's space is given back to the system when the process
316 terminates.
318 @node Changing Block Size
319 @subsection Changing the Size of a Block
320 @cindex changing the size of a block (@code{malloc})
322 Often you do not know for certain how big a block you will ultimately need
323 at the time you must begin to use the block.  For example, the block might
324 be a buffer that you use to hold a line being read from a file; no matter
325 how long you make the buffer initially, you may encounter a line that is
326 longer.
328 You can make the block longer by calling @code{realloc}.  This function
329 is declared in @file{stdlib.h}.
330 @pindex stdlib.h
332 @comment malloc.h stdlib.h
333 @comment ISO
334 @deftypefun {void *} realloc (void *@var{ptr}, size_t @var{newsize})
335 The @code{realloc} function changes the size of the block whose address is
336 @var{ptr} to be @var{newsize}.
338 Since the space after the end of the block may be in use, @code{realloc}
339 may find it necessary to copy the block to a new address where more free
340 space is available.  The value of @code{realloc} is the new address of the
341 block.  If the block needs to be moved, @code{realloc} copies the old
342 contents.
344 If you pass a null pointer for @var{ptr}, @code{realloc} behaves just
345 like @samp{malloc (@var{newsize})}.  This can be convenient, but beware
346 that older implementations (before @w{ISO C}) may not support this
347 behavior, and will probably crash when @code{realloc} is passed a null
348 pointer.
349 @end deftypefun
351 Like @code{malloc}, @code{realloc} may return a null pointer if no
352 memory space is available to make the block bigger.  When this happens,
353 the original block is untouched; it has not been modified or relocated.
355 In most cases it makes no difference what happens to the original block
356 when @code{realloc} fails, because the application program cannot continue
357 when it is out of memory, and the only thing to do is to give a fatal error
358 message.  Often it is convenient to write and use a subroutine,
359 conventionally called @code{xrealloc}, that takes care of the error message
360 as @code{xmalloc} does for @code{malloc}:
362 @smallexample
363 void *
364 xrealloc (void *ptr, size_t size)
366   register void *value = realloc (ptr, size);
367   if (value == 0)
368     fatal ("Virtual memory exhausted");
369   return value;
371 @end smallexample
373 You can also use @code{realloc} to make a block smaller.  The reason you
374 would do this is to avoid tying up a lot of memory space when only a little
375 is needed.
376 @comment The following is no longer true with the new malloc.
377 @comment But it seems wise to keep the warning for other implementations.
378 In several allocation implementations, making a block smaller sometimes
379 necessitates copying it, so it can fail if no other space is available.
381 If the new size you specify is the same as the old size, @code{realloc}
382 is guaranteed to change nothing and return the same address that you gave.
384 @node Allocating Cleared Space
385 @subsection Allocating Cleared Space
387 The function @code{calloc} allocates memory and clears it to zero.  It
388 is declared in @file{stdlib.h}.
389 @pindex stdlib.h
391 @comment malloc.h stdlib.h
392 @comment ISO
393 @deftypefun {void *} calloc (size_t @var{count}, size_t @var{eltsize})
394 This function allocates a block long enough to contain a vector of
395 @var{count} elements, each of size @var{eltsize}.  Its contents are
396 cleared to zero before @code{calloc} returns.
397 @end deftypefun
399 You could define @code{calloc} as follows:
401 @smallexample
402 void *
403 calloc (size_t count, size_t eltsize)
405   size_t size = count * eltsize;
406   void *value = malloc (size);
407   if (value != 0)
408     memset (value, 0, size);
409   return value;
411 @end smallexample
413 But in general, it is not guaranteed that @code{calloc} calls
414 @code{malloc} internally.  Therefore, if an application provides its own
415 @code{malloc}/@code{realloc}/@code{free} outside the C library, it
416 should always define @code{calloc}, too.
418 @node Efficiency and Malloc
419 @subsection Efficiency Considerations for @code{malloc}
420 @cindex efficiency and @code{malloc}
422 @ignore
424 @c No longer true, see below instead.
425 To make the best use of @code{malloc}, it helps to know that the GNU
426 version of @code{malloc} always dispenses small amounts of memory in
427 blocks whose sizes are powers of two.  It keeps separate pools for each
428 power of two.  This holds for sizes up to a page size.  Therefore, if
429 you are free to choose the size of a small block in order to make
430 @code{malloc} more efficient, make it a power of two.
431 @c !!! xref getpagesize
433 Once a page is split up for a particular block size, it can't be reused
434 for another size unless all the blocks in it are freed.  In many
435 programs, this is unlikely to happen.  Thus, you can sometimes make a
436 program use memory more efficiently by using blocks of the same size for
437 many different purposes.
439 When you ask for memory blocks of a page or larger, @code{malloc} uses a
440 different strategy; it rounds the size up to a multiple of a page, and
441 it can coalesce and split blocks as needed.
443 The reason for the two strategies is that it is important to allocate
444 and free small blocks as fast as possible, but speed is less important
445 for a large block since the program normally spends a fair amount of
446 time using it.  Also, large blocks are normally fewer in number.
447 Therefore, for large blocks, it makes sense to use a method which takes
448 more time to minimize the wasted space.
450 @end ignore
452 As apposed to other versions, the @code{malloc} in GNU libc does not
453 round up block sizes to powers of two, neither for large nor for small
454 sizes.  Neighboring chunks can be coalesced on a @code{free} no matter
455 what their size is.  This makes the implementation suitable for all
456 kinds of allocation patterns without generally incurring high memory
457 waste through fragmentation.
459 Very large blocks (much larger than a page) are allocated with
460 @code{mmap} (anonymous or via @code{/dev/zero}) by this implementation.
461 This has the great advantage that these chunks are returned to the
462 system immediately when they are freed.  Therefore, it cannot happen
463 that a large chunk becomes ``locked'' in between smaller ones and even
464 after calling @code{free} wastes memory.  The size threshold for
465 @code{mmap} to be used can be adjusted with @code{mallopt}.  The use of
466 @code{mmap} can also be disabled completely.
468 @node Aligned Memory Blocks
469 @subsection Allocating Aligned Memory Blocks
471 @cindex page boundary
472 @cindex alignment (with @code{malloc})
473 @pindex stdlib.h
474 The address of a block returned by @code{malloc} or @code{realloc} in
475 the GNU system is always a multiple of eight (or sixteen on 64-bit
476 systems).  If you need a block whose address is a multiple of a higher
477 power of two than that, use @code{memalign} or @code{valloc}.  These
478 functions are declared in @file{stdlib.h}.
480 With the GNU library, you can use @code{free} to free the blocks that
481 @code{memalign} and @code{valloc} return.  That does not work in BSD,
482 however---BSD does not provide any way to free such blocks.
484 @comment malloc.h stdlib.h
485 @comment BSD
486 @deftypefun {void *} memalign (size_t @var{boundary}, size_t @var{size})
487 The @code{memalign} function allocates a block of @var{size} bytes whose
488 address is a multiple of @var{boundary}.  The @var{boundary} must be a
489 power of two!  The function @code{memalign} works by allocating a
490 somewhat larger block, and then returning an address within the block
491 that is on the specified boundary.
492 @end deftypefun
494 @comment malloc.h stdlib.h
495 @comment BSD
496 @deftypefun {void *} valloc (size_t @var{size})
497 Using @code{valloc} is like using @code{memalign} and passing the page size
498 as the value of the second argument.  It is implemented like this:
500 @smallexample
501 void *
502 valloc (size_t size)
504   return memalign (getpagesize (), size);
506 @end smallexample
507 @c !!! xref getpagesize
508 @end deftypefun
510 @node Malloc Tunable Parameters
511 @subsection Malloc Tunable Parameters
513 You can adjust some parameters for dynamic memory allocation with the
514 @code{mallopt} function.  This function is the general SVID/XPG
515 interface, defined in @file{malloc.h}.
516 @pindex malloc.h
518 @deftypefun int mallopt (int @var{param}, int @var{value})
519 When calling @code{mallopt}, the @var{param} argument specifies the
520 parameter to be set, and @var{value} the new value to be set.  Possible
521 choices for @var{param}, as defined in @file{malloc.h}, are:
523 @table @code
524 @item M_TRIM_THRESHOLD
525 This is the minimum size (in bytes) of the top-most, releaseable chunk
526 that will cause @code{sbrk} to be called with a negative argument in
527 order to return memory to the system.
528 @item M_TOP_PAD
529 This parameter determines the amount of extra memory to obtain from the
530 system when a call to @code{sbrk} is required.  It also specifies the
531 number of bytes to retain when shrinking the heap by calling @code{sbrk}
532 with a negative argument.  This provides the necessary hysteresis in
533 heap size such that excessive amounts of system calls can be avoided.
534 @item M_MMAP_THRESHOLD
535 All chunks larger than this value are allocated outside the normal
536 heap, using the @code{mmap} system call.  This way it is guaranteed
537 that the memory for these chunks can be returned to the system on
538 @code{free}.
539 @item M_MMAP_MAX
540 The maximum number of chunks to allocate with @code{mmap}.  Setting this
541 to zero disables all use of @code{mmap}.
542 @end table
544 @end deftypefun
546 @node Heap Consistency Checking
547 @subsection Heap Consistency Checking
549 @cindex heap consistency checking
550 @cindex consistency checking, of heap
552 You can ask @code{malloc} to check the consistency of dynamic storage by
553 using the @code{mcheck} function.  This function is a GNU extension,
554 declared in @file{mcheck.h}.
555 @pindex mcheck.h
557 @comment mcheck.h
558 @comment GNU
559 @deftypefun int mcheck (void (*@var{abortfn}) (enum mcheck_status @var{status}))
560 Calling @code{mcheck} tells @code{malloc} to perform occasional
561 consistency checks.  These will catch things such as writing
562 past the end of a block that was allocated with @code{malloc}.
564 The @var{abortfn} argument is the function to call when an inconsistency
565 is found.  If you supply a null pointer, then @code{mcheck} uses a
566 default function which prints a message and calls @code{abort}
567 (@pxref{Aborting a Program}).  The function you supply is called with
568 one argument, which says what sort of inconsistency was detected; its
569 type is described below.
571 It is too late to begin allocation checking once you have allocated
572 anything with @code{malloc}.  So @code{mcheck} does nothing in that
573 case.  The function returns @code{-1} if you call it too late, and
574 @code{0} otherwise (when it is successful).
576 The easiest way to arrange to call @code{mcheck} early enough is to use
577 the option @samp{-lmcheck} when you link your program; then you don't
578 need to modify your program source at all.
579 @end deftypefun
581 @deftypefun {enum mcheck_status} mprobe (void *@var{pointer})
582 The @code{mprobe} function lets you explicitly check for inconsistencies
583 in a particular allocated block.  You must have already called
584 @code{mcheck} at the beginning of the program, to do its occasional
585 checks; calling @code{mprobe} requests an additional consistency check
586 to be done at the time of the call.
588 The argument @var{pointer} must be a pointer returned by @code{malloc}
589 or @code{realloc}.  @code{mprobe} returns a value that says what
590 inconsistency, if any, was found.  The values are described below.
591 @end deftypefun
593 @deftp {Data Type} {enum mcheck_status}
594 This enumerated type describes what kind of inconsistency was detected
595 in an allocated block, if any.  Here are the possible values:
597 @table @code
598 @item MCHECK_DISABLED
599 @code{mcheck} was not called before the first allocation.
600 No consistency checking can be done.
601 @item MCHECK_OK
602 No inconsistency detected.
603 @item MCHECK_HEAD
604 The data immediately before the block was modified.
605 This commonly happens when an array index or pointer
606 is decremented too far.
607 @item MCHECK_TAIL
608 The data immediately after the block was modified.
609 This commonly happens when an array index or pointer
610 is incremented too far.
611 @item MCHECK_FREE
612 The block was already freed.
613 @end table
614 @end deftp
616 Another possibility to check for and guard against bugs in the use of
617 @code{malloc}, @code{realloc} and @code{free} is to set the environment
618 variable @code{MALLOC_CHECK_}.  When @code{MALLOC_CHECK_} is set, a
619 special (less efficient) implementation is used which is designed to be
620 tolerant against simple errors, such as double calls of @code{free} with
621 the same argument, or overruns of a single byte (off-by-one bugs).  Not
622 all such errors can be proteced against, however, and memory leaks can
623 result.  If @code{MALLOC_CHECK_} is set to @code{0}, any detected heap
624 corruption is silently ignored; if set to @code{1}, a diagnostic is
625 printed on @code{stderr}; if set to @code{2}, @code{abort} is called
626 immediately.  This can be useful because otherwise a crash may happen
627 much later, and the true cause for the problem is then very hard to
628 track down.
630 So, what's the difference between using @code{MALLOC_CHECK_} and linking
631 with @samp{-lmcheck}?  @code{MALLOC_CHECK_} is orthognal with respect to
632 @samp{-lmcheck}.  @samp{-lmcheck} has been added for backward
633 compatibility.  Both @code{MALLOC_CHECK_} and @samp{-lmcheck} should
634 uncover the same bugs - but using @code{MALLOC_CHECK_} you don't need to
635 recompile your application.
637 @node Hooks for Malloc
638 @subsection Storage Allocation Hooks
639 @cindex allocation hooks, for @code{malloc}
641 The GNU C library lets you modify the behavior of @code{malloc},
642 @code{realloc}, and @code{free} by specifying appropriate hook
643 functions.  You can use these hooks to help you debug programs that use
644 dynamic storage allocation, for example.
646 The hook variables are declared in @file{malloc.h}.
647 @pindex malloc.h
649 @comment malloc.h
650 @comment GNU
651 @defvar __malloc_hook
652 The value of this variable is a pointer to function that @code{malloc}
653 uses whenever it is called.  You should define this function to look
654 like @code{malloc}; that is, like:
656 @smallexample
657 void *@var{function} (size_t @var{size}, void *@var{caller})
658 @end smallexample
660 The value of @var{caller} is the return address found on the stack when
661 the @code{malloc} function was called.  This value allows to trace the
662 memory consumption of the program.
663 @end defvar
665 @comment malloc.h
666 @comment GNU
667 @defvar __realloc_hook
668 The value of this variable is a pointer to function that @code{realloc}
669 uses whenever it is called.  You should define this function to look
670 like @code{realloc}; that is, like:
672 @smallexample
673 void *@var{function} (void *@var{ptr}, size_t @var{size}, void *@var{caller})
674 @end smallexample
676 The value of @var{caller} is the return address found on the stack when
677 the @code{realloc} function was called.  This value allows to trace the
678 memory consumption of the program.
679 @end defvar
681 @comment malloc.h
682 @comment GNU
683 @defvar __free_hook
684 The value of this variable is a pointer to function that @code{free}
685 uses whenever it is called.  You should define this function to look
686 like @code{free}; that is, like:
688 @smallexample
689 void @var{function} (void *@var{ptr}, void *@var{caller})
690 @end smallexample
692 The value of @var{caller} is the return address found on the stack when
693 the @code{free} function was called.  This value allows to trace the
694 memory consumption of the program.
695 @end defvar
697 You must make sure that the function you install as a hook for one of
698 these functions does not call that function recursively without restoring
699 the old value of the hook first!  Otherwise, your program will get stuck
700 in an infinite recursion.
702 Here is an example showing how to use @code{__malloc_hook} properly.  It
703 installs a function that prints out information every time @code{malloc}
704 is called.
706 @smallexample
707 static void *(*old_malloc_hook) (size_t);
708 static void *
709 my_malloc_hook (size_t size)
711   void *result;
712   __malloc_hook = old_malloc_hook;
713   result = malloc (size);
714   /* @r{@code{printf} might call @code{malloc}, so protect it too.} */
715   printf ("malloc (%u) returns %p\n", (unsigned int) size, result);
716   __malloc_hook = my_malloc_hook;
717   return result;
720 main ()
722   ...
723   old_malloc_hook = __malloc_hook;
724   __malloc_hook = my_malloc_hook;
725   ...
727 @end smallexample
729 The @code{mcheck} function (@pxref{Heap Consistency Checking}) works by
730 installing such hooks.
732 @c __morecore, __after_morecore_hook are undocumented
733 @c It's not clear whether to document them.
735 @node Statistics of Malloc
736 @subsection Statistics for Storage Allocation with @code{malloc}
738 @cindex allocation statistics
739 You can get information about dynamic storage allocation by calling the
740 @code{mallinfo} function.  This function and its associated data type
741 are declared in @file{malloc.h}; they are an extension of the standard
742 SVID/XPG version.
743 @pindex malloc.h
745 @comment malloc.h
746 @comment GNU
747 @deftp {Data Type} {struct mallinfo}
748 This structure type is used to return information about the dynamic
749 storage allocator.  It contains the following members:
751 @table @code
752 @item int arena
753 This is the total size of memory allocated with @code{sbrk} by
754 @code{malloc}, in bytes.
756 @item int ordblks
757 This is the number of chunks not in use.  (The storage allocator
758 internally gets chunks of memory from the operating system, and then
759 carves them up to satisfy individual @code{malloc} requests; see
760 @ref{Efficiency and Malloc}.)
762 @item int smblks
763 This field is unused.
765 @item int hblks
766 This is the total number of chunks allocated with @code{mmap}.
768 @item int hblkhd
769 This is the total size of memory allocated with @code{mmap}, in bytes.
771 @item int usmblks
772 This field is unused.
774 @item int fsmblks
775 This field is unused.
777 @item int uordblks
778 This is the total size of memory occupied by chunks handed out by
779 @code{malloc}.
781 @item int fordblks
782 This is the total size of memory occupied by free (not in use) chunks.
784 @item int keepcost
785 This is the size of the top-most, releaseable chunk that normally
786 borders the end of the heap (i.e. the ``brk'' of the process).
788 @end table
789 @end deftp
791 @comment malloc.h
792 @comment SVID
793 @deftypefun {struct mallinfo} mallinfo (void)
794 This function returns information about the current dynamic memory usage
795 in a structure of type @code{struct mallinfo}.
796 @end deftypefun
798 @node Summary of Malloc
799 @subsection Summary of @code{malloc}-Related Functions
801 Here is a summary of the functions that work with @code{malloc}:
803 @table @code
804 @item void *malloc (size_t @var{size})
805 Allocate a block of @var{size} bytes.  @xref{Basic Allocation}.
807 @item void free (void *@var{addr})
808 Free a block previously allocated by @code{malloc}.  @xref{Freeing after
809 Malloc}.
811 @item void *realloc (void *@var{addr}, size_t @var{size})
812 Make a block previously allocated by @code{malloc} larger or smaller,
813 possibly by copying it to a new location.  @xref{Changing Block Size}.
815 @item void *calloc (size_t @var{count}, size_t @var{eltsize})
816 Allocate a block of @var{count} * @var{eltsize} bytes using
817 @code{malloc}, and set its contents to zero.  @xref{Allocating Cleared
818 Space}.
820 @item void *valloc (size_t @var{size})
821 Allocate a block of @var{size} bytes, starting on a page boundary.
822 @xref{Aligned Memory Blocks}.
824 @item void *memalign (size_t @var{size}, size_t @var{boundary})
825 Allocate a block of @var{size} bytes, starting on an address that is a
826 multiple of @var{boundary}.  @xref{Aligned Memory Blocks}.
828 @item int mallopt (int @var{param}, int @var{value})
829 Adjust a tunable parameter.  @xref{Malloc Tunable Parameters}
831 @item int mcheck (void (*@var{abortfn}) (void))
832 Tell @code{malloc} to perform occasional consistency checks on
833 dynamically allocated memory, and to call @var{abortfn} when an
834 inconsistency is found.  @xref{Heap Consistency Checking}.
836 @item void *(*__malloc_hook) (size_t @var{size}, void *@var{caller})
837 A pointer to a function that @code{malloc} uses whenever it is called.
839 @item void *(*__realloc_hook) (void *@var{ptr}, size_t @var{size}, void *@var{caller})
840 A pointer to a function that @code{realloc} uses whenever it is called.
842 @item void (*__free_hook) (void *@var{ptr}, void *@var{caller})
843 A pointer to a function that @code{free} uses whenever it is called.
845 @item struct mallinfo mallinfo (void)
846 Return information about the current dynamic memory usage.
847 @xref{Statistics of Malloc}.
848 @end table
850 @node Allocation Debugging
851 @section Allocation Debugging
852 @cindex allocation debugging
853 @cindex malloc debugger
855 An complicated task when programming with languages which do not use
856 garbage collected dynamic memory allocation is to find memory leaks.
857 Long running programs must assure that dynamically allocated objects are
858 freed at the end of their lifetime.  If this does not happen the system
859 runs out of memory, sooner or later.
861 The @code{malloc} implementation in the GNU C library provides some
862 simple means to detect sich leaks and provide some information to find
863 the location.  To do this the application must be started in a special
864 mode which is enabled by an environment variable.  There are no speed
865 penalties if the program is compiled in preparation of the debugging if
866 the debug mode is not enabled.
868 @menu
869 * Tracing malloc::               How to install the tracing functionality.
870 * Using the Memory Debugger::    Example programs excerpts.
871 * Tips for the Memory Debugger:: Some more or less clever ideas.
872 * Interpreting the traces::      What do all these lines mean?
873 @end menu
875 @node Tracing malloc
876 @subsection How to install the tracing functionality
878 @comment mcheck.h
879 @comment GNU
880 @deftypefun void mtrace (void)
881 When the @code{mtrace} function is called it looks for an environment
882 variable named @code{MALLOC_TRACE}.  This variable is supposed to
883 contain a valid file name.  The user must have write access.  If the
884 file already exists it is truncated.  If the environment variable is not
885 set or it does not name a valid file which can be opened for writing
886 nothing is done.  The behaviour of @code{malloc} etc. is not changed.
887 For obvious reasons this also happens if the application is install SUID
888 or SGID.
890 If the named file is successfully opened @code{mtrace} installs special
891 handlers for the functions @code{malloc}, @code{realloc}, and
892 @code{free} (@pxref{Hooks for Malloc}).  From now on all uses of these
893 functions are traced and protocolled into the file.  There is now of
894 course a speed penalty for all calls to the traced functions so that the
895 tracing should not be enabled during their normal use.
897 This function is a GNU extension and generally not available on other
898 systems.  The prototype can be found in @file{mcheck.h}.
899 @end deftypefun
901 @comment mcheck.h
902 @comment GNU
903 @deftypefun void muntrace (void)
904 The @code{muntrace} function can be called after @code{mtrace} was used
905 to enable tracing the @code{malloc} calls.  If no (succesful) call of
906 @code{mtrace} was made @code{muntrace} does nothing.
908 Otherwise it deinstalls the handlers for @code{malloc}, @code{realloc},
909 and @code{free} and then closes the protocol file.  No calls are
910 protocolled anymore and the programs runs again with the full speed.
912 This function is a GNU extension and generally not available on other
913 systems.  The prototype can be found in @file{mcheck.h}.
914 @end deftypefun
916 @node Using the Memory Debugger
917 @subsection Example programs excerpts
919 Even though the tracing functionality does not influence the runtime
920 behaviour of the program it is no wise idea to call @code{mtrace} in all
921 programs.  Just imagine you debug a program using @code{mtrace} and all
922 other programs used in the debug sessions also trace their @code{malloc}
923 calls.  The output file would be the same for all programs and so is
924 unusable.  Therefore one should call @code{mtrace} only if compiled for
925 debugging.  A program could therefore start like this:
927 @example
928 #include <mcheck.h>
931 main (int argc, char *argv[])
933 #ifdef DEBUGGING
934   mtrace ();
935 #endif
936   @dots{}
938 @end example
940 This is all what is needed if you want to trace the calls during the
941 whole runtime of the program.  Alternatively you can stop the tracing at
942 any time with a call to @code{muntrace}.  It is even possible to restart
943 the tracing again with a new call to @code{mtrace}.  But this can course
944 unreliable results since there are possibly calls of the functions which
945 are not called.  Please note that not only the application uses the
946 traced functions, also libraries (including the C library itself) use
947 this function.
949 This last point is also why it is no good idea to call @code{muntrace}
950 before the program terminated.  The libraries are informed about the
951 termination of the program only after the program returns from
952 @code{main} or calls @code{exit} and so cannot free the memory they use
953 before this time.
955 So the best thing one can do is to call @code{mtrace} as the very first
956 function in the program and never call @code{muntrace}.  So the program
957 traces almost all uses of the @code{malloc} functions (except those
958 calls which are executed by constructors of the program or used
959 libraries).
961 @node Tips for the Memory Debugger
962 @subsection Some more or less clever ideas
964 You know the situation.  The program is prepared for debugging and in
965 all debugging sessions it runs well.  But once it is started without
966 debugging the error shows up.  In our situation here: the memory leaks
967 becomes visible only when we just turned off the debugging.  If you
968 foresee such situations you can still win.  Simply use something
969 equivalent to the following little program:
971 @example
972 #include <mcheck.h>
973 #include <signal.h>
975 static void
976 enable (int sig)
978   mtrace ();
979   signal (SIGUSR1, enable);
982 static void
983 disable (int sig)
985   muntrace ();
986   signal (SIGUSR2, disable);
990 main (int argc, char *argv[])
992   @dots{}
994   signal (SIGUSR1, enable);
995   signal (SIGUSR2, disable);
997   @dots{}
999 @end example
1001 I.e., the user can start the memory debugger any time s/he wants if the
1002 program was started with @code{MALLOC_TRACE} set in the environment.
1003 The output will of course not show the allocations which happened before
1004 the first signal but if there is a memory leak this will show up
1005 nevertheless.
1007 @node Interpreting the traces
1008 @subsection Interpreting the traces
1010 If you take a look at the output it will look similar to this:
1012 @example
1013 = Start
1014 @ [0x8048209] - 0x8064cc8
1015 @ [0x8048209] - 0x8064ce0
1016 @ [0x8048209] - 0x8064cf8
1017 @ [0x80481eb] + 0x8064c48 0x14
1018 @ [0x80481eb] + 0x8064c60 0x14
1019 @ [0x80481eb] + 0x8064c78 0x14
1020 @ [0x80481eb] + 0x8064c90 0x14
1021 = End
1022 @end example
1024 What this all means is not really important since the trace file is not
1025 meant to be read by a human.  Therefore no attention is payed to good
1026 readability.  Instead there is a program which comes with the GNU C
1027 library which interprets the traces and outputs a summary in on
1028 user-friendly way.  The program is called @code{mtrace} (it is in fact a
1029 Perl script) and it takes one or two arguments.  In any case the name of
1030 the file with the trace output must be specified.  If an optional argument
1031 precedes the name of the trace file this must be the name of the program
1032 which generated the trace.
1034 @example
1035 drepper$ mtrace tst-mtrace log
1036 No memory leaks.
1037 @end example
1039 In this case the program @code{tst-mtrace} was run and it produced a
1040 trace file @file{log}.  The message printed by @code{mtrace} shows there
1041 are no problems with the code, all allocated memory was freed
1042 afterwards.
1044 If we call @code{mtrace} on the example trace given above we would get a
1045 different outout:
1047 @example
1048 drepper$ mtrace errlog
1049 - 0x08064cc8 Free 2 was never alloc'd 0x8048209
1050 - 0x08064ce0 Free 3 was never alloc'd 0x8048209
1051 - 0x08064cf8 Free 4 was never alloc'd 0x8048209
1053 Memory not freed:
1054 -----------------
1055    Address     Size     Caller
1056 0x08064c48     0x14  at 0x80481eb
1057 0x08064c60     0x14  at 0x80481eb
1058 0x08064c78     0x14  at 0x80481eb
1059 0x08064c90     0x14  at 0x80481eb
1060 @end example
1062 We have called @code{mtrace} with only one argument and so the script
1063 has no chance to find out what is meant with the addresses given in the
1064 trace.  We can do better:
1066 @example
1067 drepper$ mtrace tst-mtrace errlog
1068 - 0x08064cc8 Free 2 was never alloc'd /home/drepper/tst-mtrace.c:39
1069 - 0x08064ce0 Free 3 was never alloc'd /home/drepper/tst-mtrace.c:39
1070 - 0x08064cf8 Free 4 was never alloc'd /home/drepper/tst-mtrace.c:39
1072 Memory not freed:
1073 -----------------
1074    Address     Size     Caller
1075 0x08064c48     0x14  at /home/drepper/tst-mtrace.c:33
1076 0x08064c60     0x14  at /home/drepper/tst-mtrace.c:33
1077 0x08064c78     0x14  at /home/drepper/tst-mtrace.c:33
1078 0x08064c90     0x14  at /home/drepper/tst-mtrace.c:33
1079 @end example
1081 Suddenly the output makes much more sense and the user can see
1082 immediately where the function calls causing the trouble can be found.
1084 Interpreting this output is not complicated.  There are at most two
1085 different situations being detected.  First, @code{free} was called for
1086 pointers which were never returned by one of the allocation functions.
1087 This is usually a very bad problem and how this looks like is shown in
1088 the first three lines of the output.  Situations like this are quite
1089 rare and if they appear they show up very drastically: the program
1090 normally crashes.
1092 The other situation which is much harder to detect are memory leaks.  As
1093 you can see in the output the @code{mtrace} function collects all this
1094 information and so can say that the program calls an allocation function
1095 from line 33 in the source file @file{/home/drepper/tst-mtrace.c} four
1096 times without freeing this memory before the program terminates.
1097 Whether this is a real problem keeps to be investigated.
1099 @node Obstacks
1100 @section Obstacks
1101 @cindex obstacks
1103 An @dfn{obstack} is a pool of memory containing a stack of objects.  You
1104 can create any number of separate obstacks, and then allocate objects in
1105 specified obstacks.  Within each obstack, the last object allocated must
1106 always be the first one freed, but distinct obstacks are independent of
1107 each other.
1109 Aside from this one constraint of order of freeing, obstacks are totally
1110 general: an obstack can contain any number of objects of any size.  They
1111 are implemented with macros, so allocation is usually very fast as long as
1112 the objects are usually small.  And the only space overhead per object is
1113 the padding needed to start each object on a suitable boundary.
1115 @menu
1116 * Creating Obstacks::           How to declare an obstack in your program.
1117 * Preparing for Obstacks::      Preparations needed before you can
1118                                  use obstacks.
1119 * Allocation in an Obstack::    Allocating objects in an obstack.
1120 * Freeing Obstack Objects::     Freeing objects in an obstack.
1121 * Obstack Functions::           The obstack functions are both
1122                                  functions and macros.
1123 * Growing Objects::             Making an object bigger by stages.
1124 * Extra Fast Growing::          Extra-high-efficiency (though more
1125                                  complicated) growing objects.
1126 * Status of an Obstack::        Inquiries about the status of an obstack.
1127 * Obstacks Data Alignment::     Controlling alignment of objects in obstacks.
1128 * Obstack Chunks::              How obstacks obtain and release chunks;
1129                                  efficiency considerations.
1130 * Summary of Obstacks::
1131 @end menu
1133 @node Creating Obstacks
1134 @subsection Creating Obstacks
1136 The utilities for manipulating obstacks are declared in the header
1137 file @file{obstack.h}.
1138 @pindex obstack.h
1140 @comment obstack.h
1141 @comment GNU
1142 @deftp {Data Type} {struct obstack}
1143 An obstack is represented by a data structure of type @code{struct
1144 obstack}.  This structure has a small fixed size; it records the status
1145 of the obstack and how to find the space in which objects are allocated.
1146 It does not contain any of the objects themselves.  You should not try
1147 to access the contents of the structure directly; use only the functions
1148 described in this chapter.
1149 @end deftp
1151 You can declare variables of type @code{struct obstack} and use them as
1152 obstacks, or you can allocate obstacks dynamically like any other kind
1153 of object.  Dynamic allocation of obstacks allows your program to have a
1154 variable number of different stacks.  (You can even allocate an
1155 obstack structure in another obstack, but this is rarely useful.)
1157 All the functions that work with obstacks require you to specify which
1158 obstack to use.  You do this with a pointer of type @code{struct obstack
1159 *}.  In the following, we often say ``an obstack'' when strictly
1160 speaking the object at hand is such a pointer.
1162 The objects in the obstack are packed into large blocks called
1163 @dfn{chunks}.  The @code{struct obstack} structure points to a chain of
1164 the chunks currently in use.
1166 The obstack library obtains a new chunk whenever you allocate an object
1167 that won't fit in the previous chunk.  Since the obstack library manages
1168 chunks automatically, you don't need to pay much attention to them, but
1169 you do need to supply a function which the obstack library should use to
1170 get a chunk.  Usually you supply a function which uses @code{malloc}
1171 directly or indirectly.  You must also supply a function to free a chunk.
1172 These matters are described in the following section.
1174 @node Preparing for Obstacks
1175 @subsection Preparing for Using Obstacks
1177 Each source file in which you plan to use the obstack functions
1178 must include the header file @file{obstack.h}, like this:
1180 @smallexample
1181 #include <obstack.h>
1182 @end smallexample
1184 @findex obstack_chunk_alloc
1185 @findex obstack_chunk_free
1186 Also, if the source file uses the macro @code{obstack_init}, it must
1187 declare or define two functions or macros that will be called by the
1188 obstack library.  One, @code{obstack_chunk_alloc}, is used to allocate
1189 the chunks of memory into which objects are packed.  The other,
1190 @code{obstack_chunk_free}, is used to return chunks when the objects in
1191 them are freed.  These macros should appear before any use of obstacks
1192 in the source file.
1194 Usually these are defined to use @code{malloc} via the intermediary
1195 @code{xmalloc} (@pxref{Unconstrained Allocation}).  This is done with
1196 the following pair of macro definitions:
1198 @smallexample
1199 #define obstack_chunk_alloc xmalloc
1200 #define obstack_chunk_free free
1201 @end smallexample
1203 @noindent
1204 Though the storage you get using obstacks really comes from @code{malloc},
1205 using obstacks is faster because @code{malloc} is called less often, for
1206 larger blocks of memory.  @xref{Obstack Chunks}, for full details.
1208 At run time, before the program can use a @code{struct obstack} object
1209 as an obstack, it must initialize the obstack by calling
1210 @code{obstack_init}.
1212 @comment obstack.h
1213 @comment GNU
1214 @deftypefun int obstack_init (struct obstack *@var{obstack-ptr})
1215 Initialize obstack @var{obstack-ptr} for allocation of objects.  This
1216 function calls the obstack's @code{obstack_chunk_alloc} function.  It
1217 returns 0 if @code{obstack_chunk_alloc} returns a null pointer, meaning
1218 that it is out of memory.  Otherwise, it returns 1.  If you supply an
1219 @code{obstack_chunk_alloc} function that calls @code{exit}
1220 (@pxref{Program Termination}) or @code{longjmp} (@pxref{Non-Local
1221 Exits}) when out of memory, you can safely ignore the value that
1222 @code{obstack_init} returns.
1223 @end deftypefun
1225 Here are two examples of how to allocate the space for an obstack and
1226 initialize it.  First, an obstack that is a static variable:
1228 @smallexample
1229 static struct obstack myobstack;
1230 @dots{}
1231 obstack_init (&myobstack);
1232 @end smallexample
1234 @noindent
1235 Second, an obstack that is itself dynamically allocated:
1237 @smallexample
1238 struct obstack *myobstack_ptr
1239   = (struct obstack *) xmalloc (sizeof (struct obstack));
1241 obstack_init (myobstack_ptr);
1242 @end smallexample
1244 @node Allocation in an Obstack
1245 @subsection Allocation in an Obstack
1246 @cindex allocation (obstacks)
1248 The most direct way to allocate an object in an obstack is with
1249 @code{obstack_alloc}, which is invoked almost like @code{malloc}.
1251 @comment obstack.h
1252 @comment GNU
1253 @deftypefun {void *} obstack_alloc (struct obstack *@var{obstack-ptr}, int @var{size})
1254 This allocates an uninitialized block of @var{size} bytes in an obstack
1255 and returns its address.  Here @var{obstack-ptr} specifies which obstack
1256 to allocate the block in; it is the address of the @code{struct obstack}
1257 object which represents the obstack.  Each obstack function or macro
1258 requires you to specify an @var{obstack-ptr} as the first argument.
1260 This function calls the obstack's @code{obstack_chunk_alloc} function if
1261 it needs to allocate a new chunk of memory; it returns a null pointer if
1262 @code{obstack_chunk_alloc} returns one.  In that case, it has not
1263 changed the amount of memory allocated in the obstack.  If you supply an
1264 @code{obstack_chunk_alloc} function that calls @code{exit}
1265 (@pxref{Program Termination}) or @code{longjmp} (@pxref{Non-Local
1266 Exits}) when out of memory, then @code{obstack_alloc} will never return
1267 a null pointer.
1268 @end deftypefun
1270 For example, here is a function that allocates a copy of a string @var{str}
1271 in a specific obstack, which is in the variable @code{string_obstack}:
1273 @smallexample
1274 struct obstack string_obstack;
1276 char *
1277 copystring (char *string)
1279   size_t len = strlen (string) + 1;
1280   char *s = (char *) obstack_alloc (&string_obstack, len);
1281   memcpy (s, string, len);
1282   return s;
1284 @end smallexample
1286 To allocate a block with specified contents, use the function
1287 @code{obstack_copy}, declared like this:
1289 @comment obstack.h
1290 @comment GNU
1291 @deftypefun {void *} obstack_copy (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1292 This allocates a block and initializes it by copying @var{size}
1293 bytes of data starting at @var{address}.  It can return a null pointer
1294 under the same conditions as @code{obstack_alloc}.
1295 @end deftypefun
1297 @comment obstack.h
1298 @comment GNU
1299 @deftypefun {void *} obstack_copy0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1300 Like @code{obstack_copy}, but appends an extra byte containing a null
1301 character.  This extra byte is not counted in the argument @var{size}.
1302 @end deftypefun
1304 The @code{obstack_copy0} function is convenient for copying a sequence
1305 of characters into an obstack as a null-terminated string.  Here is an
1306 example of its use:
1308 @smallexample
1309 char *
1310 obstack_savestring (char *addr, int size)
1312   return obstack_copy0 (&myobstack, addr, size);
1314 @end smallexample
1316 @noindent
1317 Contrast this with the previous example of @code{savestring} using
1318 @code{malloc} (@pxref{Basic Allocation}).
1320 @node Freeing Obstack Objects
1321 @subsection Freeing Objects in an Obstack
1322 @cindex freeing (obstacks)
1324 To free an object allocated in an obstack, use the function
1325 @code{obstack_free}.  Since the obstack is a stack of objects, freeing
1326 one object automatically frees all other objects allocated more recently
1327 in the same obstack.
1329 @comment obstack.h
1330 @comment GNU
1331 @deftypefun void obstack_free (struct obstack *@var{obstack-ptr}, void *@var{object})
1332 If @var{object} is a null pointer, everything allocated in the obstack
1333 is freed.  Otherwise, @var{object} must be the address of an object
1334 allocated in the obstack.  Then @var{object} is freed, along with
1335 everything allocated in @var{obstack} since @var{object}.
1336 @end deftypefun
1338 Note that if @var{object} is a null pointer, the result is an
1339 uninitialized obstack.  To free all storage in an obstack but leave it
1340 valid for further allocation, call @code{obstack_free} with the address
1341 of the first object allocated on the obstack:
1343 @smallexample
1344 obstack_free (obstack_ptr, first_object_allocated_ptr);
1345 @end smallexample
1347 Recall that the objects in an obstack are grouped into chunks.  When all
1348 the objects in a chunk become free, the obstack library automatically
1349 frees the chunk (@pxref{Preparing for Obstacks}).  Then other
1350 obstacks, or non-obstack allocation, can reuse the space of the chunk.
1352 @node Obstack Functions
1353 @subsection Obstack Functions and Macros
1354 @cindex macros
1356 The interfaces for using obstacks may be defined either as functions or
1357 as macros, depending on the compiler.  The obstack facility works with
1358 all C compilers, including both @w{ISO C} and traditional C, but there are
1359 precautions you must take if you plan to use compilers other than GNU C.
1361 If you are using an old-fashioned @w{non-ISO C} compiler, all the obstack
1362 ``functions'' are actually defined only as macros.  You can call these
1363 macros like functions, but you cannot use them in any other way (for
1364 example, you cannot take their address).
1366 Calling the macros requires a special precaution: namely, the first
1367 operand (the obstack pointer) may not contain any side effects, because
1368 it may be computed more than once.  For example, if you write this:
1370 @smallexample
1371 obstack_alloc (get_obstack (), 4);
1372 @end smallexample
1374 @noindent
1375 you will find that @code{get_obstack} may be called several times.
1376 If you use @code{*obstack_list_ptr++} as the obstack pointer argument,
1377 you will get very strange results since the incrementation may occur
1378 several times.
1380 In @w{ISO C}, each function has both a macro definition and a function
1381 definition.  The function definition is used if you take the address of the
1382 function without calling it.  An ordinary call uses the macro definition by
1383 default, but you can request the function definition instead by writing the
1384 function name in parentheses, as shown here:
1386 @smallexample
1387 char *x;
1388 void *(*funcp) ();
1389 /* @r{Use the macro}.  */
1390 x = (char *) obstack_alloc (obptr, size);
1391 /* @r{Call the function}.  */
1392 x = (char *) (obstack_alloc) (obptr, size);
1393 /* @r{Take the address of the function}.  */
1394 funcp = obstack_alloc;
1395 @end smallexample
1397 @noindent
1398 This is the same situation that exists in @w{ISO C} for the standard library
1399 functions.  @xref{Macro Definitions}.
1401 @strong{Warning:} When you do use the macros, you must observe the
1402 precaution of avoiding side effects in the first operand, even in @w{ISO C}.
1404 If you use the GNU C compiler, this precaution is not necessary, because
1405 various language extensions in GNU C permit defining the macros so as to
1406 compute each argument only once.
1408 @node Growing Objects
1409 @subsection Growing Objects
1410 @cindex growing objects (in obstacks)
1411 @cindex changing the size of a block (obstacks)
1413 Because storage in obstack chunks is used sequentially, it is possible to
1414 build up an object step by step, adding one or more bytes at a time to the
1415 end of the object.  With this technique, you do not need to know how much
1416 data you will put in the object until you come to the end of it.  We call
1417 this the technique of @dfn{growing objects}.  The special functions
1418 for adding data to the growing object are described in this section.
1420 You don't need to do anything special when you start to grow an object.
1421 Using one of the functions to add data to the object automatically
1422 starts it.  However, it is necessary to say explicitly when the object is
1423 finished.  This is done with the function @code{obstack_finish}.
1425 The actual address of the object thus built up is not known until the
1426 object is finished.  Until then, it always remains possible that you will
1427 add so much data that the object must be copied into a new chunk.
1429 While the obstack is in use for a growing object, you cannot use it for
1430 ordinary allocation of another object.  If you try to do so, the space
1431 already added to the growing object will become part of the other object.
1433 @comment obstack.h
1434 @comment GNU
1435 @deftypefun void obstack_blank (struct obstack *@var{obstack-ptr}, int @var{size})
1436 The most basic function for adding to a growing object is
1437 @code{obstack_blank}, which adds space without initializing it.
1438 @end deftypefun
1440 @comment obstack.h
1441 @comment GNU
1442 @deftypefun void obstack_grow (struct obstack *@var{obstack-ptr}, void *@var{data}, int @var{size})
1443 To add a block of initialized space, use @code{obstack_grow}, which is
1444 the growing-object analogue of @code{obstack_copy}.  It adds @var{size}
1445 bytes of data to the growing object, copying the contents from
1446 @var{data}.
1447 @end deftypefun
1449 @comment obstack.h
1450 @comment GNU
1451 @deftypefun void obstack_grow0 (struct obstack *@var{obstack-ptr}, void *@var{data}, int @var{size})
1452 This is the growing-object analogue of @code{obstack_copy0}.  It adds
1453 @var{size} bytes copied from @var{data}, followed by an additional null
1454 character.
1455 @end deftypefun
1457 @comment obstack.h
1458 @comment GNU
1459 @deftypefun void obstack_1grow (struct obstack *@var{obstack-ptr}, char @var{c})
1460 To add one character at a time, use the function @code{obstack_1grow}.
1461 It adds a single byte containing @var{c} to the growing object.
1462 @end deftypefun
1464 @comment obstack.h
1465 @comment GNU
1466 @deftypefun void obstack_ptr_grow (struct obstack *@var{obstack-ptr}, void *@var{data})
1467 Adding the value of a pointer one can use the function
1468 @code{obstack_ptr_grow}.  It adds @code{sizeof (void *)} bytes
1469 containing the value of @var{data}.
1470 @end deftypefun
1472 @comment obstack.h
1473 @comment GNU
1474 @deftypefun void obstack_int_grow (struct obstack *@var{obstack-ptr}, int @var{data})
1475 A single value of type @code{int} can be added by using the
1476 @code{obstack_int_grow} function.  It adds @code{sizeof (int)} bytes to
1477 the growing object and initializes them with the value of @var{data}.
1478 @end deftypefun
1480 @comment obstack.h
1481 @comment GNU
1482 @deftypefun {void *} obstack_finish (struct obstack *@var{obstack-ptr})
1483 When you are finished growing the object, use the function
1484 @code{obstack_finish} to close it off and return its final address.
1486 Once you have finished the object, the obstack is available for ordinary
1487 allocation or for growing another object.
1489 This function can return a null pointer under the same conditions as
1490 @code{obstack_alloc} (@pxref{Allocation in an Obstack}).
1491 @end deftypefun
1493 When you build an object by growing it, you will probably need to know
1494 afterward how long it became.  You need not keep track of this as you grow
1495 the object, because you can find out the length from the obstack just
1496 before finishing the object with the function @code{obstack_object_size},
1497 declared as follows:
1499 @comment obstack.h
1500 @comment GNU
1501 @deftypefun int obstack_object_size (struct obstack *@var{obstack-ptr})
1502 This function returns the current size of the growing object, in bytes.
1503 Remember to call this function @emph{before} finishing the object.
1504 After it is finished, @code{obstack_object_size} will return zero.
1505 @end deftypefun
1507 If you have started growing an object and wish to cancel it, you should
1508 finish it and then free it, like this:
1510 @smallexample
1511 obstack_free (obstack_ptr, obstack_finish (obstack_ptr));
1512 @end smallexample
1514 @noindent
1515 This has no effect if no object was growing.
1517 @cindex shrinking objects
1518 You can use @code{obstack_blank} with a negative size argument to make
1519 the current object smaller.  Just don't try to shrink it beyond zero
1520 length---there's no telling what will happen if you do that.
1522 @node Extra Fast Growing
1523 @subsection Extra Fast Growing Objects
1524 @cindex efficiency and obstacks
1526 The usual functions for growing objects incur overhead for checking
1527 whether there is room for the new growth in the current chunk.  If you
1528 are frequently constructing objects in small steps of growth, this
1529 overhead can be significant.
1531 You can reduce the overhead by using special ``fast growth''
1532 functions that grow the object without checking.  In order to have a
1533 robust program, you must do the checking yourself.  If you do this checking
1534 in the simplest way each time you are about to add data to the object, you
1535 have not saved anything, because that is what the ordinary growth
1536 functions do.  But if you can arrange to check less often, or check
1537 more efficiently, then you make the program faster.
1539 The function @code{obstack_room} returns the amount of room available
1540 in the current chunk.  It is declared as follows:
1542 @comment obstack.h
1543 @comment GNU
1544 @deftypefun int obstack_room (struct obstack *@var{obstack-ptr})
1545 This returns the number of bytes that can be added safely to the current
1546 growing object (or to an object about to be started) in obstack
1547 @var{obstack} using the fast growth functions.
1548 @end deftypefun
1550 While you know there is room, you can use these fast growth functions
1551 for adding data to a growing object:
1553 @comment obstack.h
1554 @comment GNU
1555 @deftypefun void obstack_1grow_fast (struct obstack *@var{obstack-ptr}, char @var{c})
1556 The function @code{obstack_1grow_fast} adds one byte containing the
1557 character @var{c} to the growing object in obstack @var{obstack-ptr}.
1558 @end deftypefun
1560 @comment obstack.h
1561 @comment GNU
1562 @deftypefun void obstack_ptr_grow_fast (struct obstack *@var{obstack-ptr}, void *@var{data})
1563 The function @code{obstack_ptr_grow_fast} adds @code{sizeof (void *)}
1564 bytes containing the value of @var{data} to the growing object in
1565 obstack @var{obstack-ptr}.
1566 @end deftypefun
1568 @comment obstack.h
1569 @comment GNU
1570 @deftypefun void obstack_int_grow_fast (struct obstack *@var{obstack-ptr}, int @var{data})
1571 The function @code{obstack_int_grow_fast} adds @code{sizeof (int)} bytes
1572 containing the value of @var{data} to the growing object in obstack
1573 @var{obstack-ptr}.
1574 @end deftypefun
1576 @comment obstack.h
1577 @comment GNU
1578 @deftypefun void obstack_blank_fast (struct obstack *@var{obstack-ptr}, int @var{size})
1579 The function @code{obstack_blank_fast} adds @var{size} bytes to the
1580 growing object in obstack @var{obstack-ptr} without initializing them.
1581 @end deftypefun
1583 When you check for space using @code{obstack_room} and there is not
1584 enough room for what you want to add, the fast growth functions
1585 are not safe.  In this case, simply use the corresponding ordinary
1586 growth function instead.  Very soon this will copy the object to a
1587 new chunk; then there will be lots of room available again.
1589 So, each time you use an ordinary growth function, check afterward for
1590 sufficient space using @code{obstack_room}.  Once the object is copied
1591 to a new chunk, there will be plenty of space again, so the program will
1592 start using the fast growth functions again.
1594 Here is an example:
1596 @smallexample
1597 @group
1598 void
1599 add_string (struct obstack *obstack, const char *ptr, int len)
1601   while (len > 0)
1602     @{
1603       int room = obstack_room (obstack);
1604       if (room == 0)
1605         @{
1606           /* @r{Not enough room. Add one character slowly,}
1607              @r{which may copy to a new chunk and make room.}  */
1608           obstack_1grow (obstack, *ptr++);
1609           len--;
1610         @}
1611       else
1612         @{
1613           if (room > len)
1614             room = len;
1615           /* @r{Add fast as much as we have room for.} */
1616           len -= room;
1617           while (room-- > 0)
1618             obstack_1grow_fast (obstack, *ptr++);
1619         @}
1620     @}
1622 @end group
1623 @end smallexample
1625 @node Status of an Obstack
1626 @subsection Status of an Obstack
1627 @cindex obstack status
1628 @cindex status of obstack
1630 Here are functions that provide information on the current status of
1631 allocation in an obstack.  You can use them to learn about an object while
1632 still growing it.
1634 @comment obstack.h
1635 @comment GNU
1636 @deftypefun {void *} obstack_base (struct obstack *@var{obstack-ptr})
1637 This function returns the tentative address of the beginning of the
1638 currently growing object in @var{obstack-ptr}.  If you finish the object
1639 immediately, it will have that address.  If you make it larger first, it
1640 may outgrow the current chunk---then its address will change!
1642 If no object is growing, this value says where the next object you
1643 allocate will start (once again assuming it fits in the current
1644 chunk).
1645 @end deftypefun
1647 @comment obstack.h
1648 @comment GNU
1649 @deftypefun {void *} obstack_next_free (struct obstack *@var{obstack-ptr})
1650 This function returns the address of the first free byte in the current
1651 chunk of obstack @var{obstack-ptr}.  This is the end of the currently
1652 growing object.  If no object is growing, @code{obstack_next_free}
1653 returns the same value as @code{obstack_base}.
1654 @end deftypefun
1656 @comment obstack.h
1657 @comment GNU
1658 @deftypefun int obstack_object_size (struct obstack *@var{obstack-ptr})
1659 This function returns the size in bytes of the currently growing object.
1660 This is equivalent to
1662 @smallexample
1663 obstack_next_free (@var{obstack-ptr}) - obstack_base (@var{obstack-ptr})
1664 @end smallexample
1665 @end deftypefun
1667 @node Obstacks Data Alignment
1668 @subsection Alignment of Data in Obstacks
1669 @cindex alignment (in obstacks)
1671 Each obstack has an @dfn{alignment boundary}; each object allocated in
1672 the obstack automatically starts on an address that is a multiple of the
1673 specified boundary.  By default, this boundary is 4 bytes.
1675 To access an obstack's alignment boundary, use the macro
1676 @code{obstack_alignment_mask}, whose function prototype looks like
1677 this:
1679 @comment obstack.h
1680 @comment GNU
1681 @deftypefn Macro int obstack_alignment_mask (struct obstack *@var{obstack-ptr})
1682 The value is a bit mask; a bit that is 1 indicates that the corresponding
1683 bit in the address of an object should be 0.  The mask value should be one
1684 less than a power of 2; the effect is that all object addresses are
1685 multiples of that power of 2.  The default value of the mask is 3, so that
1686 addresses are multiples of 4.  A mask value of 0 means an object can start
1687 on any multiple of 1 (that is, no alignment is required).
1689 The expansion of the macro @code{obstack_alignment_mask} is an lvalue,
1690 so you can alter the mask by assignment.  For example, this statement:
1692 @smallexample
1693 obstack_alignment_mask (obstack_ptr) = 0;
1694 @end smallexample
1696 @noindent
1697 has the effect of turning off alignment processing in the specified obstack.
1698 @end deftypefn
1700 Note that a change in alignment mask does not take effect until
1701 @emph{after} the next time an object is allocated or finished in the
1702 obstack.  If you are not growing an object, you can make the new
1703 alignment mask take effect immediately by calling @code{obstack_finish}.
1704 This will finish a zero-length object and then do proper alignment for
1705 the next object.
1707 @node Obstack Chunks
1708 @subsection Obstack Chunks
1709 @cindex efficiency of chunks
1710 @cindex chunks
1712 Obstacks work by allocating space for themselves in large chunks, and
1713 then parceling out space in the chunks to satisfy your requests.  Chunks
1714 are normally 4096 bytes long unless you specify a different chunk size.
1715 The chunk size includes 8 bytes of overhead that are not actually used
1716 for storing objects.  Regardless of the specified size, longer chunks
1717 will be allocated when necessary for long objects.
1719 The obstack library allocates chunks by calling the function
1720 @code{obstack_chunk_alloc}, which you must define.  When a chunk is no
1721 longer needed because you have freed all the objects in it, the obstack
1722 library frees the chunk by calling @code{obstack_chunk_free}, which you
1723 must also define.
1725 These two must be defined (as macros) or declared (as functions) in each
1726 source file that uses @code{obstack_init} (@pxref{Creating Obstacks}).
1727 Most often they are defined as macros like this:
1729 @smallexample
1730 #define obstack_chunk_alloc malloc
1731 #define obstack_chunk_free free
1732 @end smallexample
1734 Note that these are simple macros (no arguments).  Macro definitions with
1735 arguments will not work!  It is necessary that @code{obstack_chunk_alloc}
1736 or @code{obstack_chunk_free}, alone, expand into a function name if it is
1737 not itself a function name.
1739 If you allocate chunks with @code{malloc}, the chunk size should be a
1740 power of 2.  The default chunk size, 4096, was chosen because it is long
1741 enough to satisfy many typical requests on the obstack yet short enough
1742 not to waste too much memory in the portion of the last chunk not yet used.
1744 @comment obstack.h
1745 @comment GNU
1746 @deftypefn Macro int obstack_chunk_size (struct obstack *@var{obstack-ptr})
1747 This returns the chunk size of the given obstack.
1748 @end deftypefn
1750 Since this macro expands to an lvalue, you can specify a new chunk size by
1751 assigning it a new value.  Doing so does not affect the chunks already
1752 allocated, but will change the size of chunks allocated for that particular
1753 obstack in the future.  It is unlikely to be useful to make the chunk size
1754 smaller, but making it larger might improve efficiency if you are
1755 allocating many objects whose size is comparable to the chunk size.  Here
1756 is how to do so cleanly:
1758 @smallexample
1759 if (obstack_chunk_size (obstack_ptr) < @var{new-chunk-size})
1760   obstack_chunk_size (obstack_ptr) = @var{new-chunk-size};
1761 @end smallexample
1763 @node Summary of Obstacks
1764 @subsection Summary of Obstack Functions
1766 Here is a summary of all the functions associated with obstacks.  Each
1767 takes the address of an obstack (@code{struct obstack *}) as its first
1768 argument.
1770 @table @code
1771 @item void obstack_init (struct obstack *@var{obstack-ptr})
1772 Initialize use of an obstack.  @xref{Creating Obstacks}.
1774 @item void *obstack_alloc (struct obstack *@var{obstack-ptr}, int @var{size})
1775 Allocate an object of @var{size} uninitialized bytes.
1776 @xref{Allocation in an Obstack}.
1778 @item void *obstack_copy (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1779 Allocate an object of @var{size} bytes, with contents copied from
1780 @var{address}.  @xref{Allocation in an Obstack}.
1782 @item void *obstack_copy0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1783 Allocate an object of @var{size}+1 bytes, with @var{size} of them copied
1784 from @var{address}, followed by a null character at the end.
1785 @xref{Allocation in an Obstack}.
1787 @item void obstack_free (struct obstack *@var{obstack-ptr}, void *@var{object})
1788 Free @var{object} (and everything allocated in the specified obstack
1789 more recently than @var{object}).  @xref{Freeing Obstack Objects}.
1791 @item void obstack_blank (struct obstack *@var{obstack-ptr}, int @var{size})
1792 Add @var{size} uninitialized bytes to a growing object.
1793 @xref{Growing Objects}.
1795 @item void obstack_grow (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1796 Add @var{size} bytes, copied from @var{address}, to a growing object.
1797 @xref{Growing Objects}.
1799 @item void obstack_grow0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1800 Add @var{size} bytes, copied from @var{address}, to a growing object,
1801 and then add another byte containing a null character.  @xref{Growing
1802 Objects}.
1804 @item void obstack_1grow (struct obstack *@var{obstack-ptr}, char @var{data-char})
1805 Add one byte containing @var{data-char} to a growing object.
1806 @xref{Growing Objects}.
1808 @item void *obstack_finish (struct obstack *@var{obstack-ptr})
1809 Finalize the object that is growing and return its permanent address.
1810 @xref{Growing Objects}.
1812 @item int obstack_object_size (struct obstack *@var{obstack-ptr})
1813 Get the current size of the currently growing object.  @xref{Growing
1814 Objects}.
1816 @item void obstack_blank_fast (struct obstack *@var{obstack-ptr}, int @var{size})
1817 Add @var{size} uninitialized bytes to a growing object without checking
1818 that there is enough room.  @xref{Extra Fast Growing}.
1820 @item void obstack_1grow_fast (struct obstack *@var{obstack-ptr}, char @var{data-char})
1821 Add one byte containing @var{data-char} to a growing object without
1822 checking that there is enough room.  @xref{Extra Fast Growing}.
1824 @item int obstack_room (struct obstack *@var{obstack-ptr})
1825 Get the amount of room now available for growing the current object.
1826 @xref{Extra Fast Growing}.
1828 @item int obstack_alignment_mask (struct obstack *@var{obstack-ptr})
1829 The mask used for aligning the beginning of an object.  This is an
1830 lvalue.  @xref{Obstacks Data Alignment}.
1832 @item int obstack_chunk_size (struct obstack *@var{obstack-ptr})
1833 The size for allocating chunks.  This is an lvalue.  @xref{Obstack Chunks}.
1835 @item void *obstack_base (struct obstack *@var{obstack-ptr})
1836 Tentative starting address of the currently growing object.
1837 @xref{Status of an Obstack}.
1839 @item void *obstack_next_free (struct obstack *@var{obstack-ptr})
1840 Address just after the end of the currently growing object.
1841 @xref{Status of an Obstack}.
1842 @end table
1844 @node Variable Size Automatic
1845 @section Automatic Storage with Variable Size
1846 @cindex automatic freeing
1847 @cindex @code{alloca} function
1848 @cindex automatic storage with variable size
1850 The function @code{alloca} supports a kind of half-dynamic allocation in
1851 which blocks are allocated dynamically but freed automatically.
1853 Allocating a block with @code{alloca} is an explicit action; you can
1854 allocate as many blocks as you wish, and compute the size at run time.  But
1855 all the blocks are freed when you exit the function that @code{alloca} was
1856 called from, just as if they were automatic variables declared in that
1857 function.  There is no way to free the space explicitly.
1859 The prototype for @code{alloca} is in @file{stdlib.h}.  This function is
1860 a BSD extension.
1861 @pindex stdlib.h
1863 @comment stdlib.h
1864 @comment GNU, BSD
1865 @deftypefun {void *} alloca (size_t @var{size});
1866 The return value of @code{alloca} is the address of a block of @var{size}
1867 bytes of storage, allocated in the stack frame of the calling function.
1868 @end deftypefun
1870 Do not use @code{alloca} inside the arguments of a function call---you
1871 will get unpredictable results, because the stack space for the
1872 @code{alloca} would appear on the stack in the middle of the space for
1873 the function arguments.  An example of what to avoid is @code{foo (x,
1874 alloca (4), y)}.
1875 @c This might get fixed in future versions of GCC, but that won't make
1876 @c it safe with compilers generally.
1878 @menu
1879 * Alloca Example::              Example of using @code{alloca}.
1880 * Advantages of Alloca::        Reasons to use @code{alloca}.
1881 * Disadvantages of Alloca::     Reasons to avoid @code{alloca}.
1882 * GNU C Variable-Size Arrays::  Only in GNU C, here is an alternative
1883                                  method of allocating dynamically and
1884                                  freeing automatically.
1885 @end menu
1887 @node Alloca Example
1888 @subsection @code{alloca} Example
1890 As an example of use of @code{alloca}, here is a function that opens a file
1891 name made from concatenating two argument strings, and returns a file
1892 descriptor or minus one signifying failure:
1894 @smallexample
1896 open2 (char *str1, char *str2, int flags, int mode)
1898   char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
1899   stpcpy (stpcpy (name, str1), str2);
1900   return open (name, flags, mode);
1902 @end smallexample
1904 @noindent
1905 Here is how you would get the same results with @code{malloc} and
1906 @code{free}:
1908 @smallexample
1910 open2 (char *str1, char *str2, int flags, int mode)
1912   char *name = (char *) malloc (strlen (str1) + strlen (str2) + 1);
1913   int desc;
1914   if (name == 0)
1915     fatal ("virtual memory exceeded");
1916   stpcpy (stpcpy (name, str1), str2);
1917   desc = open (name, flags, mode);
1918   free (name);
1919   return desc;
1921 @end smallexample
1923 As you can see, it is simpler with @code{alloca}.  But @code{alloca} has
1924 other, more important advantages, and some disadvantages.
1926 @node Advantages of Alloca
1927 @subsection Advantages of @code{alloca}
1929 Here are the reasons why @code{alloca} may be preferable to @code{malloc}:
1931 @itemize @bullet
1932 @item
1933 Using @code{alloca} wastes very little space and is very fast.  (It is
1934 open-coded by the GNU C compiler.)
1936 @item
1937 Since @code{alloca} does not have separate pools for different sizes of
1938 block, space used for any size block can be reused for any other size.
1939 @code{alloca} does not cause storage fragmentation.
1941 @item
1942 @cindex longjmp
1943 Nonlocal exits done with @code{longjmp} (@pxref{Non-Local Exits})
1944 automatically free the space allocated with @code{alloca} when they exit
1945 through the function that called @code{alloca}.  This is the most
1946 important reason to use @code{alloca}.
1948 To illustrate this, suppose you have a function
1949 @code{open_or_report_error} which returns a descriptor, like
1950 @code{open}, if it succeeds, but does not return to its caller if it
1951 fails.  If the file cannot be opened, it prints an error message and
1952 jumps out to the command level of your program using @code{longjmp}.
1953 Let's change @code{open2} (@pxref{Alloca Example}) to use this
1954 subroutine:@refill
1956 @smallexample
1958 open2 (char *str1, char *str2, int flags, int mode)
1960   char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
1961   stpcpy (stpcpy (name, str1), str2);
1962   return open_or_report_error (name, flags, mode);
1964 @end smallexample
1966 @noindent
1967 Because of the way @code{alloca} works, the storage it allocates is
1968 freed even when an error occurs, with no special effort required.
1970 By contrast, the previous definition of @code{open2} (which uses
1971 @code{malloc} and @code{free}) would develop a storage leak if it were
1972 changed in this way.  Even if you are willing to make more changes to
1973 fix it, there is no easy way to do so.
1974 @end itemize
1976 @node Disadvantages of Alloca
1977 @subsection Disadvantages of @code{alloca}
1979 @cindex @code{alloca} disadvantages
1980 @cindex disadvantages of @code{alloca}
1981 These are the disadvantages of @code{alloca} in comparison with
1982 @code{malloc}:
1984 @itemize @bullet
1985 @item
1986 If you try to allocate more storage than the machine can provide, you
1987 don't get a clean error message.  Instead you get a fatal signal like
1988 the one you would get from an infinite recursion; probably a
1989 segmentation violation (@pxref{Program Error Signals}).
1991 @item
1992 Some non-GNU systems fail to support @code{alloca}, so it is less
1993 portable.  However, a slower emulation of @code{alloca} written in C
1994 is available for use on systems with this deficiency.
1995 @end itemize
1997 @node GNU C Variable-Size Arrays
1998 @subsection GNU C Variable-Size Arrays
1999 @cindex variable-sized arrays
2001 In GNU C, you can replace most uses of @code{alloca} with an array of
2002 variable size.  Here is how @code{open2} would look then:
2004 @smallexample
2005 int open2 (char *str1, char *str2, int flags, int mode)
2007   char name[strlen (str1) + strlen (str2) + 1];
2008   stpcpy (stpcpy (name, str1), str2);
2009   return open (name, flags, mode);
2011 @end smallexample
2013 But @code{alloca} is not always equivalent to a variable-sized array, for
2014 several reasons:
2016 @itemize @bullet
2017 @item
2018 A variable size array's space is freed at the end of the scope of the
2019 name of the array.  The space allocated with @code{alloca}
2020 remains until the end of the function.
2022 @item
2023 It is possible to use @code{alloca} within a loop, allocating an
2024 additional block on each iteration.  This is impossible with
2025 variable-sized arrays.
2026 @end itemize
2028 @strong{Note:} If you mix use of @code{alloca} and variable-sized arrays
2029 within one function, exiting a scope in which a variable-sized array was
2030 declared frees all blocks allocated with @code{alloca} during the
2031 execution of that scope.
2034 @node Relocating Allocator
2035 @section Relocating Allocator
2037 @cindex relocating memory allocator
2038 Any system of dynamic memory allocation has overhead: the amount of
2039 space it uses is more than the amount the program asks for.  The
2040 @dfn{relocating memory allocator} achieves very low overhead by moving
2041 blocks in memory as necessary, on its own initiative.
2043 @menu
2044 * Relocator Concepts::          How to understand relocating allocation.
2045 * Using Relocator::             Functions for relocating allocation.
2046 @end menu
2048 @node Relocator Concepts
2049 @subsection Concepts of Relocating Allocation
2051 @ifinfo
2052 The @dfn{relocating memory allocator} achieves very low overhead by
2053 moving blocks in memory as necessary, on its own initiative.
2054 @end ifinfo
2056 When you allocate a block with @code{malloc}, the address of the block
2057 never changes unless you use @code{realloc} to change its size.  Thus,
2058 you can safely store the address in various places, temporarily or
2059 permanently, as you like.  This is not safe when you use the relocating
2060 memory allocator, because any and all relocatable blocks can move
2061 whenever you allocate memory in any fashion.  Even calling @code{malloc}
2062 or @code{realloc} can move the relocatable blocks.
2064 @cindex handle
2065 For each relocatable block, you must make a @dfn{handle}---a pointer
2066 object in memory, designated to store the address of that block.  The
2067 relocating allocator knows where each block's handle is, and updates the
2068 address stored there whenever it moves the block, so that the handle
2069 always points to the block.  Each time you access the contents of the
2070 block, you should fetch its address anew from the handle.
2072 To call any of the relocating allocator functions from a signal handler
2073 is almost certainly incorrect, because the signal could happen at any
2074 time and relocate all the blocks.  The only way to make this safe is to
2075 block the signal around any access to the contents of any relocatable
2076 block---not a convenient mode of operation.  @xref{Nonreentrancy}.
2078 @node Using Relocator
2079 @subsection Allocating and Freeing Relocatable Blocks
2081 @pindex malloc.h
2082 In the descriptions below, @var{handleptr} designates the address of the
2083 handle.  All the functions are declared in @file{malloc.h}; all are GNU
2084 extensions.
2086 @comment malloc.h
2087 @comment GNU
2088 @deftypefun {void *} r_alloc (void **@var{handleptr}, size_t @var{size})
2089 This function allocates a relocatable block of size @var{size}.  It
2090 stores the block's address in @code{*@var{handleptr}} and returns
2091 a non-null pointer to indicate success.
2093 If @code{r_alloc} can't get the space needed, it stores a null pointer
2094 in @code{*@var{handleptr}}, and returns a null pointer.
2095 @end deftypefun
2097 @comment malloc.h
2098 @comment GNU
2099 @deftypefun void r_alloc_free (void **@var{handleptr})
2100 This function is the way to free a relocatable block.  It frees the
2101 block that @code{*@var{handleptr}} points to, and stores a null pointer
2102 in @code{*@var{handleptr}} to show it doesn't point to an allocated
2103 block any more.
2104 @end deftypefun
2106 @comment malloc.h
2107 @comment GNU
2108 @deftypefun {void *} r_re_alloc (void **@var{handleptr}, size_t @var{size})
2109 The function @code{r_re_alloc} adjusts the size of the block that
2110 @code{*@var{handleptr}} points to, making it @var{size} bytes long.  It
2111 stores the address of the resized block in @code{*@var{handleptr}} and
2112 returns a non-null pointer to indicate success.
2114 If enough memory is not available, this function returns a null pointer
2115 and does not modify @code{*@var{handleptr}}.
2116 @end deftypefun
2118 @ignore
2119 @comment No longer available...
2121 @comment @node Memory Warnings
2122 @comment @section Memory Usage Warnings
2123 @comment @cindex memory usage warnings
2124 @comment @cindex warnings of memory almost full
2126 @pindex malloc.c
2127 You can ask for warnings as the program approaches running out of memory
2128 space, by calling @code{memory_warnings}.  This tells @code{malloc} to
2129 check memory usage every time it asks for more memory from the operating
2130 system.  This is a GNU extension declared in @file{malloc.h}.
2132 @comment malloc.h
2133 @comment GNU
2134 @comment @deftypefun void memory_warnings (void *@var{start}, void (*@var{warn-func}) (const char *))
2135 Call this function to request warnings for nearing exhaustion of virtual
2136 memory.
2138 The argument @var{start} says where data space begins, in memory.  The
2139 allocator compares this against the last address used and against the
2140 limit of data space, to determine the fraction of available memory in
2141 use.  If you supply zero for @var{start}, then a default value is used
2142 which is right in most circumstances.
2144 For @var{warn-func}, supply a function that @code{malloc} can call to
2145 warn you.  It is called with a string (a warning message) as argument.
2146 Normally it ought to display the string for the user to read.
2147 @end deftypefun
2149 The warnings come when memory becomes 75% full, when it becomes 85%
2150 full, and when it becomes 95% full.  Above 95% you get another warning
2151 each time memory usage increases.
2153 @end ignore