Update.
[glibc.git] / manual / memory.texi
blob958e1d14c54796abd2926c6298a8346cfc528593
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 @end menu
43 @node Memory Concepts
44 @section Dynamic Memory Allocation Concepts
45 @cindex dynamic allocation
46 @cindex static allocation
47 @cindex automatic allocation
49 @dfn{Dynamic memory allocation} is a technique in which programs
50 determine as they are running where to store some information.  You need
51 dynamic allocation when the number of memory blocks you need, or how
52 long you continue to need them, depends on the data you are working on.
54 For example, you may need a block to store a line read from an input file;
55 since there is no limit to how long a line can be, you must allocate the
56 storage dynamically and make it dynamically larger as you read more of the
57 line.
59 Or, you may need a block for each record or each definition in the input
60 data; since you can't know in advance how many there will be, you must
61 allocate a new block for each record or definition as you read it.
63 When you use dynamic allocation, the allocation of a block of memory is an
64 action that the program requests explicitly.  You call a function or macro
65 when you want to allocate space, and specify the size with an argument.  If
66 you want to free the space, you do so by calling another function or macro.
67 You can do these things whenever you want, as often as you want.
69 @node Dynamic Allocation and C
70 @section Dynamic Allocation and C
72 The C language supports two kinds of memory allocation through the variables
73 in C programs:
75 @itemize @bullet
76 @item
77 @dfn{Static allocation} is what happens when you declare a static or
78 global variable.  Each static or global variable defines one block of
79 space, of a fixed size.  The space is allocated once, when your program
80 is started, and is never freed.
82 @item
83 @dfn{Automatic allocation} happens when you declare an automatic
84 variable, such as a function argument or a local variable.  The space
85 for an automatic variable is allocated when the compound statement
86 containing the declaration is entered, and is freed when that
87 compound statement is exited.
89 In GNU C, the length of the automatic storage can be an expression
90 that varies.  In other C implementations, it must be a constant.
91 @end itemize
93 Dynamic allocation is not supported by C variables; there is no storage
94 class ``dynamic'', and there can never be a C variable whose value is
95 stored in dynamically allocated space.  The only way to refer to
96 dynamically allocated space is through a pointer.  Because it is less
97 convenient, and because the actual process of dynamic allocation
98 requires more computation time, programmers generally use dynamic
99 allocation only when neither static nor automatic allocation will serve.
101 For example, if you want to allocate dynamically some space to hold a
102 @code{struct foobar}, you cannot declare a variable of type @code{struct
103 foobar} whose contents are the dynamically allocated space.  But you can
104 declare a variable of pointer type @code{struct foobar *} and assign it the
105 address of the space.  Then you can use the operators @samp{*} and
106 @samp{->} on this pointer variable to refer to the contents of the space:
108 @smallexample
110   struct foobar *ptr
111      = (struct foobar *) malloc (sizeof (struct foobar));
112   ptr->name = x;
113   ptr->next = current_foobar;
114   current_foobar = ptr;
116 @end smallexample
118 @node Unconstrained Allocation
119 @section Unconstrained Allocation
120 @cindex unconstrained storage allocation
121 @cindex @code{malloc} function
122 @cindex heap, dynamic allocation from
124 The most general dynamic allocation facility is @code{malloc}.  It
125 allows you to allocate blocks of memory of any size at any time, make
126 them bigger or smaller at any time, and free the blocks individually at
127 any time (or never).
129 @menu
130 * Basic Allocation::            Simple use of @code{malloc}.
131 * Malloc Examples::             Examples of @code{malloc}.  @code{xmalloc}.
132 * Freeing after Malloc::        Use @code{free} to free a block you
133                                  got with @code{malloc}.
134 * Changing Block Size::         Use @code{realloc} to make a block
135                                  bigger or smaller.
136 * Allocating Cleared Space::    Use @code{calloc} to allocate a
137                                  block and clear it.
138 * Efficiency and Malloc::       Efficiency considerations in use of
139                                  these functions.
140 * Aligned Memory Blocks::       Allocating specially aligned memory:
141                                  @code{memalign} and @code{valloc}.
142 * Malloc Tunable Parameters::   Use @code{mallopt} to adjust allocation
143                                  parameters.
144 * Heap Consistency Checking::   Automatic checking for errors.
145 * Hooks for Malloc::            You can use these hooks for debugging
146                                  programs that use @code{malloc}.
147 * Statistics of Malloc::        Getting information about how much
148                                  memory your program is using.
149 * Summary of Malloc::           Summary of @code{malloc} and related functions.
150 @end menu
152 @node Basic Allocation
153 @subsection Basic Storage Allocation
154 @cindex allocation of memory with @code{malloc}
156 To allocate a block of memory, call @code{malloc}.  The prototype for
157 this function is in @file{stdlib.h}.
158 @pindex stdlib.h
160 @comment malloc.h stdlib.h
161 @comment ISO
162 @deftypefun {void *} malloc (size_t @var{size})
163 This function returns a pointer to a newly allocated block @var{size}
164 bytes long, or a null pointer if the block could not be allocated.
165 @end deftypefun
167 The contents of the block are undefined; you must initialize it yourself
168 (or use @code{calloc} instead; @pxref{Allocating Cleared Space}).
169 Normally you would cast the value as a pointer to the kind of object
170 that you want to store in the block.  Here we show an example of doing
171 so, and of initializing the space with zeros using the library function
172 @code{memset} (@pxref{Copying and Concatenation}):
174 @smallexample
175 struct foo *ptr;
176 @dots{}
177 ptr = (struct foo *) malloc (sizeof (struct foo));
178 if (ptr == 0) abort ();
179 memset (ptr, 0, sizeof (struct foo));
180 @end smallexample
182 You can store the result of @code{malloc} into any pointer variable
183 without a cast, because @w{ISO C} automatically converts the type
184 @code{void *} to another type of pointer when necessary.  But the cast
185 is necessary in contexts other than assignment operators or if you might
186 want your code to run in traditional C.
188 Remember that when allocating space for a string, the argument to
189 @code{malloc} must be one plus the length of the string.  This is
190 because a string is terminated with a null character that doesn't count
191 in the ``length'' of the string but does need space.  For example:
193 @smallexample
194 char *ptr;
195 @dots{}
196 ptr = (char *) malloc (length + 1);
197 @end smallexample
199 @noindent
200 @xref{Representation of Strings}, for more information about this.
202 @node Malloc Examples
203 @subsection Examples of @code{malloc}
205 If no more space is available, @code{malloc} returns a null pointer.
206 You should check the value of @emph{every} call to @code{malloc}.  It is
207 useful to write a subroutine that calls @code{malloc} and reports an
208 error if the value is a null pointer, returning only if the value is
209 nonzero.  This function is conventionally called @code{xmalloc}.  Here
210 it is:
212 @smallexample
213 void *
214 xmalloc (size_t size)
216   register void *value = malloc (size);
217   if (value == 0)
218     fatal ("virtual memory exhausted");
219   return value;
221 @end smallexample
223 Here is a real example of using @code{malloc} (by way of @code{xmalloc}).
224 The function @code{savestring} will copy a sequence of characters into
225 a newly allocated null-terminated string:
227 @smallexample
228 @group
229 char *
230 savestring (const char *ptr, size_t len)
232   register char *value = (char *) xmalloc (len + 1);
233   value[len] = '\0';
234   return (char *) memcpy (value, ptr, len);
236 @end group
237 @end smallexample
239 The block that @code{malloc} gives you is guaranteed to be aligned so
240 that it can hold any type of data.  In the GNU system, the address is
241 always a multiple of eight on most systems, and a multiple of 16 on
242 64-bit systems.  Only rarely is any higher boundary (such as a page
243 boundary) necessary; for those cases, use @code{memalign} or
244 @code{valloc} (@pxref{Aligned Memory Blocks}).
246 Note that the memory located after the end of the block is likely to be
247 in use for something else; perhaps a block already allocated by another
248 call to @code{malloc}.  If you attempt to treat the block as longer than
249 you asked for it to be, you are liable to destroy the data that
250 @code{malloc} uses to keep track of its blocks, or you may destroy the
251 contents of another block.  If you have already allocated a block and
252 discover you want it to be bigger, use @code{realloc} (@pxref{Changing
253 Block Size}).
255 @node Freeing after Malloc
256 @subsection Freeing Memory Allocated with @code{malloc}
257 @cindex freeing memory allocated with @code{malloc}
258 @cindex heap, freeing memory from
260 When you no longer need a block that you got with @code{malloc}, use the
261 function @code{free} to make the block available to be allocated again.
262 The prototype for this function is in @file{stdlib.h}.
263 @pindex stdlib.h
265 @comment malloc.h stdlib.h
266 @comment ISO
267 @deftypefun void free (void *@var{ptr})
268 The @code{free} function deallocates the block of storage pointed at
269 by @var{ptr}.
270 @end deftypefun
272 @comment stdlib.h
273 @comment Sun
274 @deftypefun void cfree (void *@var{ptr})
275 This function does the same thing as @code{free}.  It's provided for
276 backward compatibility with SunOS; you should use @code{free} instead.
277 @end deftypefun
279 Freeing a block alters the contents of the block.  @strong{Do not expect to
280 find any data (such as a pointer to the next block in a chain of blocks) in
281 the block after freeing it.}  Copy whatever you need out of the block before
282 freeing it!  Here is an example of the proper way to free all the blocks in
283 a chain, and the strings that they point to:
285 @smallexample
286 struct chain
287   @{
288     struct chain *next;
289     char *name;
290   @}
292 void
293 free_chain (struct chain *chain)
295   while (chain != 0)
296     @{
297       struct chain *next = chain->next;
298       free (chain->name);
299       free (chain);
300       chain = next;
301     @}
303 @end smallexample
305 Occasionally, @code{free} can actually return memory to the operating
306 system and make the process smaller.  Usually, all it can do is allow a
307 later call to @code{malloc} to reuse the space.  In the meantime, the
308 space remains in your program as part of a free-list used internally by
309 @code{malloc}.
311 There is no point in freeing blocks at the end of a program, because all
312 of the program's space is given back to the system when the process
313 terminates.
315 @node Changing Block Size
316 @subsection Changing the Size of a Block
317 @cindex changing the size of a block (@code{malloc})
319 Often you do not know for certain how big a block you will ultimately need
320 at the time you must begin to use the block.  For example, the block might
321 be a buffer that you use to hold a line being read from a file; no matter
322 how long you make the buffer initially, you may encounter a line that is
323 longer.
325 You can make the block longer by calling @code{realloc}.  This function
326 is declared in @file{stdlib.h}.
327 @pindex stdlib.h
329 @comment malloc.h stdlib.h
330 @comment ISO
331 @deftypefun {void *} realloc (void *@var{ptr}, size_t @var{newsize})
332 The @code{realloc} function changes the size of the block whose address is
333 @var{ptr} to be @var{newsize}.
335 Since the space after the end of the block may be in use, @code{realloc}
336 may find it necessary to copy the block to a new address where more free
337 space is available.  The value of @code{realloc} is the new address of the
338 block.  If the block needs to be moved, @code{realloc} copies the old
339 contents.
341 If you pass a null pointer for @var{ptr}, @code{realloc} behaves just
342 like @samp{malloc (@var{newsize})}.  This can be convenient, but beware
343 that older implementations (before @w{ISO C}) may not support this
344 behavior, and will probably crash when @code{realloc} is passed a null
345 pointer.
346 @end deftypefun
348 Like @code{malloc}, @code{realloc} may return a null pointer if no
349 memory space is available to make the block bigger.  When this happens,
350 the original block is untouched; it has not been modified or relocated.
352 In most cases it makes no difference what happens to the original block
353 when @code{realloc} fails, because the application program cannot continue
354 when it is out of memory, and the only thing to do is to give a fatal error
355 message.  Often it is convenient to write and use a subroutine,
356 conventionally called @code{xrealloc}, that takes care of the error message
357 as @code{xmalloc} does for @code{malloc}:
359 @smallexample
360 void *
361 xrealloc (void *ptr, size_t size)
363   register void *value = realloc (ptr, size);
364   if (value == 0)
365     fatal ("Virtual memory exhausted");
366   return value;
368 @end smallexample
370 You can also use @code{realloc} to make a block smaller.  The reason you
371 would do this is to avoid tying up a lot of memory space when only a little
372 is needed.
373 @comment The following is no longer true with the new malloc.
374 @comment But it seems wise to keep the warning for other implementations.
375 In several allocation implementations, making a block smaller sometimes
376 necessitates copying it, so it can fail if no other space is available.
378 If the new size you specify is the same as the old size, @code{realloc}
379 is guaranteed to change nothing and return the same address that you gave.
381 @node Allocating Cleared Space
382 @subsection Allocating Cleared Space
384 The function @code{calloc} allocates memory and clears it to zero.  It
385 is declared in @file{stdlib.h}.
386 @pindex stdlib.h
388 @comment malloc.h stdlib.h
389 @comment ISO
390 @deftypefun {void *} calloc (size_t @var{count}, size_t @var{eltsize})
391 This function allocates a block long enough to contain a vector of
392 @var{count} elements, each of size @var{eltsize}.  Its contents are
393 cleared to zero before @code{calloc} returns.
394 @end deftypefun
396 You could define @code{calloc} as follows:
398 @smallexample
399 void *
400 calloc (size_t count, size_t eltsize)
402   size_t size = count * eltsize;
403   void *value = malloc (size);
404   if (value != 0)
405     memset (value, 0, size);
406   return value;
408 @end smallexample
410 But in general, it is not guaranteed that @code{calloc} calls
411 @code{malloc} internally.  Therefore, if an application provides its own
412 @code{malloc}/@code{realloc}/@code{free} outside the C library, it
413 should always define @code{calloc}, too.
415 @node Efficiency and Malloc
416 @subsection Efficiency Considerations for @code{malloc}
417 @cindex efficiency and @code{malloc}
419 @ignore
421 @c No longer true, see below instead.
422 To make the best use of @code{malloc}, it helps to know that the GNU
423 version of @code{malloc} always dispenses small amounts of memory in
424 blocks whose sizes are powers of two.  It keeps separate pools for each
425 power of two.  This holds for sizes up to a page size.  Therefore, if
426 you are free to choose the size of a small block in order to make
427 @code{malloc} more efficient, make it a power of two.
428 @c !!! xref getpagesize
430 Once a page is split up for a particular block size, it can't be reused
431 for another size unless all the blocks in it are freed.  In many
432 programs, this is unlikely to happen.  Thus, you can sometimes make a
433 program use memory more efficiently by using blocks of the same size for
434 many different purposes.
436 When you ask for memory blocks of a page or larger, @code{malloc} uses a
437 different strategy; it rounds the size up to a multiple of a page, and
438 it can coalesce and split blocks as needed.
440 The reason for the two strategies is that it is important to allocate
441 and free small blocks as fast as possible, but speed is less important
442 for a large block since the program normally spends a fair amount of
443 time using it.  Also, large blocks are normally fewer in number.
444 Therefore, for large blocks, it makes sense to use a method which takes
445 more time to minimize the wasted space.
447 @end ignore
449 As apposed to other versions, the @code{malloc} in GNU libc does not
450 round up block sizes to powers of two, neither for large nor for small
451 sizes.  Neighboring chunks can be coalesced on a @code{free} no matter
452 what their size is.  This makes the implementation suitable for all
453 kinds of allocation patterns without generally incurring high memory
454 waste through fragmentation.
456 Very large blocks (much larger than a page) are allocated with
457 @code{mmap} (anonymous or via @code{/dev/zero}) by this implementation.
458 This has the great advantage that these chunks are returned to the
459 system immediately when they are freed.  Therefore, it cannot happen
460 that a large chunk becomes ``locked'' in between smaller ones and even
461 after calling @code{free} wastes memory.  The size threshold for
462 @code{mmap} to be used can be adjusted with @code{mallopt}.  The use of
463 @code{mmap} can also be disabled completely.
465 @node Aligned Memory Blocks
466 @subsection Allocating Aligned Memory Blocks
468 @cindex page boundary
469 @cindex alignment (with @code{malloc})
470 @pindex stdlib.h
471 The address of a block returned by @code{malloc} or @code{realloc} in
472 the GNU system is always a multiple of eight (or sixteen on 64-bit
473 systems).  If you need a block whose address is a multiple of a higher
474 power of two than that, use @code{memalign} or @code{valloc}.  These
475 functions are declared in @file{stdlib.h}.
477 With the GNU library, you can use @code{free} to free the blocks that
478 @code{memalign} and @code{valloc} return.  That does not work in BSD,
479 however---BSD does not provide any way to free such blocks.
481 @comment malloc.h stdlib.h
482 @comment BSD
483 @deftypefun {void *} memalign (size_t @var{boundary}, size_t @var{size})
484 The @code{memalign} function allocates a block of @var{size} bytes whose
485 address is a multiple of @var{boundary}.  The @var{boundary} must be a
486 power of two!  The function @code{memalign} works by allocating a
487 somewhat larger block, and then returning an address within the block
488 that is on the specified boundary.
489 @end deftypefun
491 @comment malloc.h stdlib.h
492 @comment BSD
493 @deftypefun {void *} valloc (size_t @var{size})
494 Using @code{valloc} is like using @code{memalign} and passing the page size
495 as the value of the second argument.  It is implemented like this:
497 @smallexample
498 void *
499 valloc (size_t size)
501   return memalign (getpagesize (), size);
503 @end smallexample
504 @c !!! xref getpagesize
505 @end deftypefun
507 @node Malloc Tunable Parameters
508 @subsection Malloc Tunable Parameters
510 You can adjust some parameters for dynamic memory allocation with the
511 @code{mallopt} function.  This function is the general SVID/XPG
512 interface, defined in @file{malloc.h}.
513 @pindex malloc.h
515 @deftypefun int mallopt (int @var{param}, int @var{value})
516 When calling @code{mallopt}, the @var{param} argument specifies the
517 parameter to be set, and @var{value} the new value to be set.  Possible
518 choices for @var{param}, as defined in @file{malloc.h}, are:
520 @table @code
521 @item M_TRIM_THRESHOLD
522 This is the minimum size (in bytes) of the top-most, releaseable chunk
523 that will cause @code{sbrk} to be called with a negative argument in
524 order to return memory to the system.
525 @item M_TOP_PAD
526 This parameter determines the amount of extra memory to obtain from the
527 system when a call to @code{sbrk} is required.  It also specifies the
528 number of bytes to retain when shrinking the heap by calling @code{sbrk}
529 with a negative argument.  This provides the necessary hysteresis in
530 heap size such that excessive amounts of system calls can be avoided.
531 @item M_MMAP_THRESHOLD
532 All chunks larger than this value are allocated outside the normal
533 heap, using the @code{mmap} system call.  This way it is guaranteed
534 that the memory for these chunks can be returned to the system on
535 @code{free}.
536 @item M_MMAP_MAX
537 The maximum number of chunks to allocate with @code{mmap}.  Setting this
538 to zero disables all use of @code{mmap}.
539 @end table
541 @end deftypefun
543 @node Heap Consistency Checking
544 @subsection Heap Consistency Checking
546 @cindex heap consistency checking
547 @cindex consistency checking, of heap
549 You can ask @code{malloc} to check the consistency of dynamic storage by
550 using the @code{mcheck} function.  This function is a GNU extension,
551 declared in @file{mcheck.h}.
552 @pindex mcheck.h
554 @comment mcheck.h
555 @comment GNU
556 @deftypefun int mcheck (void (*@var{abortfn}) (enum mcheck_status @var{status}))
557 Calling @code{mcheck} tells @code{malloc} to perform occasional
558 consistency checks.  These will catch things such as writing
559 past the end of a block that was allocated with @code{malloc}.
561 The @var{abortfn} argument is the function to call when an inconsistency
562 is found.  If you supply a null pointer, then @code{mcheck} uses a
563 default function which prints a message and calls @code{abort}
564 (@pxref{Aborting a Program}).  The function you supply is called with
565 one argument, which says what sort of inconsistency was detected; its
566 type is described below.
568 It is too late to begin allocation checking once you have allocated
569 anything with @code{malloc}.  So @code{mcheck} does nothing in that
570 case.  The function returns @code{-1} if you call it too late, and
571 @code{0} otherwise (when it is successful).
573 The easiest way to arrange to call @code{mcheck} early enough is to use
574 the option @samp{-lmcheck} when you link your program; then you don't
575 need to modify your program source at all.  Alternately you might use
576 a debugger to insert a call to @code{mcheck} whenever the program is
577 started, for example these gdb commands will automatically call @code{mcheck}
578 whenever the program starts:
580 @smallexample
581 (gdb) break main
582 Breakpoint 1, main (argc=2, argv=0xbffff964) at whatever.c:10
583 (gdb) command 1
584 Type commands for when breakpoint 1 is hit, one per line.
585 End with a line saying just "end".
586 >call mcheck(0)
587 >continue
588 >end
589 (gdb) ...
590 @end smallexample
592 This will however only work if no initialization function of any object
593 involved calls any of the @code{malloc} functions since @code{mcheck}
594 must be called before the first such function.
596 @end deftypefun
598 @deftypefun {enum mcheck_status} mprobe (void *@var{pointer})
599 The @code{mprobe} function lets you explicitly check for inconsistencies
600 in a particular allocated block.  You must have already called
601 @code{mcheck} at the beginning of the program, to do its occasional
602 checks; calling @code{mprobe} requests an additional consistency check
603 to be done at the time of the call.
605 The argument @var{pointer} must be a pointer returned by @code{malloc}
606 or @code{realloc}.  @code{mprobe} returns a value that says what
607 inconsistency, if any, was found.  The values are described below.
608 @end deftypefun
610 @deftp {Data Type} {enum mcheck_status}
611 This enumerated type describes what kind of inconsistency was detected
612 in an allocated block, if any.  Here are the possible values:
614 @table @code
615 @item MCHECK_DISABLED
616 @code{mcheck} was not called before the first allocation.
617 No consistency checking can be done.
618 @item MCHECK_OK
619 No inconsistency detected.
620 @item MCHECK_HEAD
621 The data immediately before the block was modified.
622 This commonly happens when an array index or pointer
623 is decremented too far.
624 @item MCHECK_TAIL
625 The data immediately after the block was modified.
626 This commonly happens when an array index or pointer
627 is incremented too far.
628 @item MCHECK_FREE
629 The block was already freed.
630 @end table
631 @end deftp
633 Another possibility to check for and guard against bugs in the use of
634 @code{malloc}, @code{realloc} and @code{free} is to set the environment
635 variable @code{MALLOC_CHECK_}.  When @code{MALLOC_CHECK_} is set, a
636 special (less efficient) implementation is used which is designed to be
637 tolerant against simple errors, such as double calls of @code{free} with
638 the same argument, or overruns of a single byte (off-by-one bugs).  Not
639 all such errors can be proteced against, however, and memory leaks can
640 result.  If @code{MALLOC_CHECK_} is set to @code{0}, any detected heap
641 corruption is silently ignored; if set to @code{1}, a diagnostic is
642 printed on @code{stderr}; if set to @code{2}, @code{abort} is called
643 immediately.  This can be useful because otherwise a crash may happen
644 much later, and the true cause for the problem is then very hard to
645 track down.
647 So, what's the difference between using @code{MALLOC_CHECK_} and linking
648 with @samp{-lmcheck}?  @code{MALLOC_CHECK_} is orthognal with respect to
649 @samp{-lmcheck}.  @samp{-lmcheck} has been added for backward
650 compatibility.  Both @code{MALLOC_CHECK_} and @samp{-lmcheck} should
651 uncover the same bugs - but using @code{MALLOC_CHECK_} you don't need to
652 recompile your application.
654 @node Hooks for Malloc
655 @subsection Storage Allocation Hooks
656 @cindex allocation hooks, for @code{malloc}
658 The GNU C library lets you modify the behavior of @code{malloc},
659 @code{realloc}, and @code{free} by specifying appropriate hook
660 functions.  You can use these hooks to help you debug programs that use
661 dynamic storage allocation, for example.
663 The hook variables are declared in @file{malloc.h}.
664 @pindex malloc.h
666 @comment malloc.h
667 @comment GNU
668 @defvar __malloc_hook
669 The value of this variable is a pointer to function that @code{malloc}
670 uses whenever it is called.  You should define this function to look
671 like @code{malloc}; that is, like:
673 @smallexample
674 void *@var{function} (size_t @var{size}, void *@var{caller})
675 @end smallexample
677 The value of @var{caller} is the return address found on the stack when
678 the @code{malloc} function was called.  This value allows to trace the
679 memory consumption of the program.
680 @end defvar
682 @comment malloc.h
683 @comment GNU
684 @defvar __realloc_hook
685 The value of this variable is a pointer to function that @code{realloc}
686 uses whenever it is called.  You should define this function to look
687 like @code{realloc}; that is, like:
689 @smallexample
690 void *@var{function} (void *@var{ptr}, size_t @var{size}, void *@var{caller})
691 @end smallexample
693 The value of @var{caller} is the return address found on the stack when
694 the @code{realloc} function was called.  This value allows to trace the
695 memory consumption of the program.
696 @end defvar
698 @comment malloc.h
699 @comment GNU
700 @defvar __free_hook
701 The value of this variable is a pointer to function that @code{free}
702 uses whenever it is called.  You should define this function to look
703 like @code{free}; that is, like:
705 @smallexample
706 void @var{function} (void *@var{ptr}, void *@var{caller})
707 @end smallexample
709 The value of @var{caller} is the return address found on the stack when
710 the @code{free} function was called.  This value allows to trace the
711 memory consumption of the program.
712 @end defvar
714 @comment malloc.h
715 @comment GNU
716 @defvar __memalign_hook
717 The value of this variable is a pointer to function that @code{memalign}
718 uses whenever it is called.  You should define this function to look
719 like @code{memalign}; that is, like:
721 @smallexample
722 void *@var{function} (size_t @var{size}, size_t @var{alignment})
723 @end smallexample
724 @end defvar
726 You must make sure that the function you install as a hook for one of
727 these functions does not call that function recursively without restoring
728 the old value of the hook first!  Otherwise, your program will get stuck
729 in an infinite recursion.  Before calling the function recursively, one
730 should make sure to restore all the hooks to their previous value.  When
731 coming back from the recursive call, all the hooks should be resaved
732 since a hook might modify itself.
734 Here is an example showing how to use @code{__malloc_hook} and
735 @code{__free_hook} properly.  It installs a function that prints out
736 information every time @code{malloc} or @code{free} is called.  We just
737 assume here that @code{realloc} and @code{memalign} are not used in our
738 program.
740 @smallexample
741 /* Global variables used to hold underlaying hook values.  */
742 static void *(*old_malloc_hook) (size_t);
743 static void (*old_free_hook) (void*);
745 /* Prototypes for our hooks.  */
746 static void *my_malloc_hook (size_t);
747 static void my_free_hook(void*);
749 static void *
750 my_malloc_hook (size_t size)
752   void *result;
753   /* Restore all old hooks */
754   __malloc_hook = old_malloc_hook;
755   __free_hook = old_free_hook;
756   /* Call recursively */
757   result = malloc (size);
758   /* Save underlaying hooks */
759   old_malloc_hook = __malloc_hook;
760   old_free_hook = __free_hook;
761   /* @r{@code{printf} might call @code{malloc}, so protect it too.} */
762   printf ("malloc (%u) returns %p\n", (unsigned int) size, result);
763   /* Restore our own hooks */
764   __malloc_hook = my_malloc_hook;
765   __free_hook = my_free_hook;
766   return result;
769 static void *
770 my_free_hook (void *ptr)
772   /* Restore all old hooks */
773   __malloc_hook = old_malloc_hook;
774   __free_hook = old_free_hook;
775   /* Call recursively */
776   free (ptr);
777   /* Save underlaying hooks */
778   old_malloc_hook = __malloc_hook;
779   old_free_hook = __free_hook;
780   /* @r{@code{printf} might call @code{free}, so protect it too.} */
781   printf ("freed pointer %p\n", ptr);
782   /* Restore our own hooks */
783   __malloc_hook = my_malloc_hook;
784   __free_hook = my_free_hook;
787 main ()
789   ...
790   old_malloc_hook = __malloc_hook;
791   old_free_hook = __free_hook;
792   __malloc_hook = my_malloc_hook;
793   __free_hook = my_free_hook;
794   ...
796 @end smallexample
798 The @code{mcheck} function (@pxref{Heap Consistency Checking}) works by
799 installing such hooks.
801 @c __morecore, __after_morecore_hook are undocumented
802 @c It's not clear whether to document them.
804 @node Statistics of Malloc
805 @subsection Statistics for Storage Allocation with @code{malloc}
807 @cindex allocation statistics
808 You can get information about dynamic storage allocation by calling the
809 @code{mallinfo} function.  This function and its associated data type
810 are declared in @file{malloc.h}; they are an extension of the standard
811 SVID/XPG version.
812 @pindex malloc.h
814 @comment malloc.h
815 @comment GNU
816 @deftp {Data Type} {struct mallinfo}
817 This structure type is used to return information about the dynamic
818 storage allocator.  It contains the following members:
820 @table @code
821 @item int arena
822 This is the total size of memory allocated with @code{sbrk} by
823 @code{malloc}, in bytes.
825 @item int ordblks
826 This is the number of chunks not in use.  (The storage allocator
827 internally gets chunks of memory from the operating system, and then
828 carves them up to satisfy individual @code{malloc} requests; see
829 @ref{Efficiency and Malloc}.)
831 @item int smblks
832 This field is unused.
834 @item int hblks
835 This is the total number of chunks allocated with @code{mmap}.
837 @item int hblkhd
838 This is the total size of memory allocated with @code{mmap}, in bytes.
840 @item int usmblks
841 This field is unused.
843 @item int fsmblks
844 This field is unused.
846 @item int uordblks
847 This is the total size of memory occupied by chunks handed out by
848 @code{malloc}.
850 @item int fordblks
851 This is the total size of memory occupied by free (not in use) chunks.
853 @item int keepcost
854 This is the size of the top-most, releaseable chunk that normally
855 borders the end of the heap (i.e. the ``brk'' of the process).
857 @end table
858 @end deftp
860 @comment malloc.h
861 @comment SVID
862 @deftypefun {struct mallinfo} mallinfo (void)
863 This function returns information about the current dynamic memory usage
864 in a structure of type @code{struct mallinfo}.
865 @end deftypefun
867 @node Summary of Malloc
868 @subsection Summary of @code{malloc}-Related Functions
870 Here is a summary of the functions that work with @code{malloc}:
872 @table @code
873 @item void *malloc (size_t @var{size})
874 Allocate a block of @var{size} bytes.  @xref{Basic Allocation}.
876 @item void free (void *@var{addr})
877 Free a block previously allocated by @code{malloc}.  @xref{Freeing after
878 Malloc}.
880 @item void *realloc (void *@var{addr}, size_t @var{size})
881 Make a block previously allocated by @code{malloc} larger or smaller,
882 possibly by copying it to a new location.  @xref{Changing Block Size}.
884 @item void *calloc (size_t @var{count}, size_t @var{eltsize})
885 Allocate a block of @var{count} * @var{eltsize} bytes using
886 @code{malloc}, and set its contents to zero.  @xref{Allocating Cleared
887 Space}.
889 @item void *valloc (size_t @var{size})
890 Allocate a block of @var{size} bytes, starting on a page boundary.
891 @xref{Aligned Memory Blocks}.
893 @item void *memalign (size_t @var{size}, size_t @var{boundary})
894 Allocate a block of @var{size} bytes, starting on an address that is a
895 multiple of @var{boundary}.  @xref{Aligned Memory Blocks}.
897 @item int mallopt (int @var{param}, int @var{value})
898 Adjust a tunable parameter.  @xref{Malloc Tunable Parameters}.
900 @item int mcheck (void (*@var{abortfn}) (void))
901 Tell @code{malloc} to perform occasional consistency checks on
902 dynamically allocated memory, and to call @var{abortfn} when an
903 inconsistency is found.  @xref{Heap Consistency Checking}.
905 @item void *(*__malloc_hook) (size_t @var{size}, void *@var{caller})
906 A pointer to a function that @code{malloc} uses whenever it is called.
908 @item void *(*__realloc_hook) (void *@var{ptr}, size_t @var{size}, void *@var{caller})
909 A pointer to a function that @code{realloc} uses whenever it is called.
911 @item void (*__free_hook) (void *@var{ptr}, void *@var{caller})
912 A pointer to a function that @code{free} uses whenever it is called.
914 @item void (*__memalign_hook) (size_t @var{size}, size_t @var{alignment})
915 A pointer to a function that @code{memalign} uses whenever it is called.
917 @item struct mallinfo mallinfo (void)
918 Return information about the current dynamic memory usage.
919 @xref{Statistics of Malloc}.
920 @end table
922 @node Allocation Debugging
923 @section Allocation Debugging
924 @cindex allocation debugging
925 @cindex malloc debugger
927 An complicated task when programming with languages which do not use
928 garbage collected dynamic memory allocation is to find memory leaks.
929 Long running programs must assure that dynamically allocated objects are
930 freed at the end of their lifetime.  If this does not happen the system
931 runs out of memory, sooner or later.
933 The @code{malloc} implementation in the GNU C library provides some
934 simple means to detect sich leaks and provide some information to find
935 the location.  To do this the application must be started in a special
936 mode which is enabled by an environment variable.  There are no speed
937 penalties if the program is compiled in preparation of the debugging if
938 the debug mode is not enabled.
940 @menu
941 * Tracing malloc::               How to install the tracing functionality.
942 * Using the Memory Debugger::    Example programs excerpts.
943 * Tips for the Memory Debugger:: Some more or less clever ideas.
944 * Interpreting the traces::      What do all these lines mean?
945 @end menu
947 @node Tracing malloc
948 @subsection How to install the tracing functionality
950 @comment mcheck.h
951 @comment GNU
952 @deftypefun void mtrace (void)
953 When the @code{mtrace} function is called it looks for an environment
954 variable named @code{MALLOC_TRACE}.  This variable is supposed to
955 contain a valid file name.  The user must have write access.  If the
956 file already exists it is truncated.  If the environment variable is not
957 set or it does not name a valid file which can be opened for writing
958 nothing is done.  The behaviour of @code{malloc} etc. is not changed.
959 For obvious reasons this also happens if the application is install SUID
960 or SGID.
962 If the named file is successfully opened @code{mtrace} installs special
963 handlers for the functions @code{malloc}, @code{realloc}, and
964 @code{free} (@pxref{Hooks for Malloc}).  From now on all uses of these
965 functions are traced and protocolled into the file.  There is now of
966 course a speed penalty for all calls to the traced functions so that the
967 tracing should not be enabled during their normal use.
969 This function is a GNU extension and generally not available on other
970 systems.  The prototype can be found in @file{mcheck.h}.
971 @end deftypefun
973 @comment mcheck.h
974 @comment GNU
975 @deftypefun void muntrace (void)
976 The @code{muntrace} function can be called after @code{mtrace} was used
977 to enable tracing the @code{malloc} calls.  If no (succesful) call of
978 @code{mtrace} was made @code{muntrace} does nothing.
980 Otherwise it deinstalls the handlers for @code{malloc}, @code{realloc},
981 and @code{free} and then closes the protocol file.  No calls are
982 protocolled anymore and the programs runs again with the full speed.
984 This function is a GNU extension and generally not available on other
985 systems.  The prototype can be found in @file{mcheck.h}.
986 @end deftypefun
988 @node Using the Memory Debugger
989 @subsection Example programs excerpts
991 Even though the tracing functionality does not influence the runtime
992 behaviour of the program it is no wise idea to call @code{mtrace} in all
993 programs.  Just imagine you debug a program using @code{mtrace} and all
994 other programs used in the debug sessions also trace their @code{malloc}
995 calls.  The output file would be the same for all programs and so is
996 unusable.  Therefore one should call @code{mtrace} only if compiled for
997 debugging.  A program could therefore start like this:
999 @example
1000 #include <mcheck.h>
1003 main (int argc, char *argv[])
1005 #ifdef DEBUGGING
1006   mtrace ();
1007 #endif
1008   @dots{}
1010 @end example
1012 This is all what is needed if you want to trace the calls during the
1013 whole runtime of the program.  Alternatively you can stop the tracing at
1014 any time with a call to @code{muntrace}.  It is even possible to restart
1015 the tracing again with a new call to @code{mtrace}.  But this can course
1016 unreliable results since there are possibly calls of the functions which
1017 are not called.  Please note that not only the application uses the
1018 traced functions, also libraries (including the C library itself) use
1019 this function.
1021 This last point is also why it is no good idea to call @code{muntrace}
1022 before the program terminated.  The libraries are informed about the
1023 termination of the program only after the program returns from
1024 @code{main} or calls @code{exit} and so cannot free the memory they use
1025 before this time.
1027 So the best thing one can do is to call @code{mtrace} as the very first
1028 function in the program and never call @code{muntrace}.  So the program
1029 traces almost all uses of the @code{malloc} functions (except those
1030 calls which are executed by constructors of the program or used
1031 libraries).
1033 @node Tips for the Memory Debugger
1034 @subsection Some more or less clever ideas
1036 You know the situation.  The program is prepared for debugging and in
1037 all debugging sessions it runs well.  But once it is started without
1038 debugging the error shows up.  In our situation here: the memory leaks
1039 becomes visible only when we just turned off the debugging.  If you
1040 foresee such situations you can still win.  Simply use something
1041 equivalent to the following little program:
1043 @example
1044 #include <mcheck.h>
1045 #include <signal.h>
1047 static void
1048 enable (int sig)
1050   mtrace ();
1051   signal (SIGUSR1, enable);
1054 static void
1055 disable (int sig)
1057   muntrace ();
1058   signal (SIGUSR2, disable);
1062 main (int argc, char *argv[])
1064   @dots{}
1066   signal (SIGUSR1, enable);
1067   signal (SIGUSR2, disable);
1069   @dots{}
1071 @end example
1073 I.e., the user can start the memory debugger any time s/he wants if the
1074 program was started with @code{MALLOC_TRACE} set in the environment.
1075 The output will of course not show the allocations which happened before
1076 the first signal but if there is a memory leak this will show up
1077 nevertheless.
1079 @node Interpreting the traces
1080 @subsection Interpreting the traces
1082 If you take a look at the output it will look similar to this:
1084 @example
1085 = Start
1086 @ [0x8048209] - 0x8064cc8
1087 @ [0x8048209] - 0x8064ce0
1088 @ [0x8048209] - 0x8064cf8
1089 @ [0x80481eb] + 0x8064c48 0x14
1090 @ [0x80481eb] + 0x8064c60 0x14
1091 @ [0x80481eb] + 0x8064c78 0x14
1092 @ [0x80481eb] + 0x8064c90 0x14
1093 = End
1094 @end example
1096 What this all means is not really important since the trace file is not
1097 meant to be read by a human.  Therefore no attention is payed to good
1098 readability.  Instead there is a program which comes with the GNU C
1099 library which interprets the traces and outputs a summary in on
1100 user-friendly way.  The program is called @code{mtrace} (it is in fact a
1101 Perl script) and it takes one or two arguments.  In any case the name of
1102 the file with the trace output must be specified.  If an optional argument
1103 precedes the name of the trace file this must be the name of the program
1104 which generated the trace.
1106 @example
1107 drepper$ mtrace tst-mtrace log
1108 No memory leaks.
1109 @end example
1111 In this case the program @code{tst-mtrace} was run and it produced a
1112 trace file @file{log}.  The message printed by @code{mtrace} shows there
1113 are no problems with the code, all allocated memory was freed
1114 afterwards.
1116 If we call @code{mtrace} on the example trace given above we would get a
1117 different outout:
1119 @example
1120 drepper$ mtrace errlog
1121 - 0x08064cc8 Free 2 was never alloc'd 0x8048209
1122 - 0x08064ce0 Free 3 was never alloc'd 0x8048209
1123 - 0x08064cf8 Free 4 was never alloc'd 0x8048209
1125 Memory not freed:
1126 -----------------
1127    Address     Size     Caller
1128 0x08064c48     0x14  at 0x80481eb
1129 0x08064c60     0x14  at 0x80481eb
1130 0x08064c78     0x14  at 0x80481eb
1131 0x08064c90     0x14  at 0x80481eb
1132 @end example
1134 We have called @code{mtrace} with only one argument and so the script
1135 has no chance to find out what is meant with the addresses given in the
1136 trace.  We can do better:
1138 @example
1139 drepper$ mtrace tst-mtrace errlog
1140 - 0x08064cc8 Free 2 was never alloc'd /home/drepper/tst-mtrace.c:39
1141 - 0x08064ce0 Free 3 was never alloc'd /home/drepper/tst-mtrace.c:39
1142 - 0x08064cf8 Free 4 was never alloc'd /home/drepper/tst-mtrace.c:39
1144 Memory not freed:
1145 -----------------
1146    Address     Size     Caller
1147 0x08064c48     0x14  at /home/drepper/tst-mtrace.c:33
1148 0x08064c60     0x14  at /home/drepper/tst-mtrace.c:33
1149 0x08064c78     0x14  at /home/drepper/tst-mtrace.c:33
1150 0x08064c90     0x14  at /home/drepper/tst-mtrace.c:33
1151 @end example
1153 Suddenly the output makes much more sense and the user can see
1154 immediately where the function calls causing the trouble can be found.
1156 Interpreting this output is not complicated.  There are at most two
1157 different situations being detected.  First, @code{free} was called for
1158 pointers which were never returned by one of the allocation functions.
1159 This is usually a very bad problem and how this looks like is shown in
1160 the first three lines of the output.  Situations like this are quite
1161 rare and if they appear they show up very drastically: the program
1162 normally crashes.
1164 The other situation which is much harder to detect are memory leaks.  As
1165 you can see in the output the @code{mtrace} function collects all this
1166 information and so can say that the program calls an allocation function
1167 from line 33 in the source file @file{/home/drepper/tst-mtrace.c} four
1168 times without freeing this memory before the program terminates.
1169 Whether this is a real problem keeps to be investigated.
1171 @node Obstacks
1172 @section Obstacks
1173 @cindex obstacks
1175 An @dfn{obstack} is a pool of memory containing a stack of objects.  You
1176 can create any number of separate obstacks, and then allocate objects in
1177 specified obstacks.  Within each obstack, the last object allocated must
1178 always be the first one freed, but distinct obstacks are independent of
1179 each other.
1181 Aside from this one constraint of order of freeing, obstacks are totally
1182 general: an obstack can contain any number of objects of any size.  They
1183 are implemented with macros, so allocation is usually very fast as long as
1184 the objects are usually small.  And the only space overhead per object is
1185 the padding needed to start each object on a suitable boundary.
1187 @menu
1188 * Creating Obstacks::           How to declare an obstack in your program.
1189 * Preparing for Obstacks::      Preparations needed before you can
1190                                  use obstacks.
1191 * Allocation in an Obstack::    Allocating objects in an obstack.
1192 * Freeing Obstack Objects::     Freeing objects in an obstack.
1193 * Obstack Functions::           The obstack functions are both
1194                                  functions and macros.
1195 * Growing Objects::             Making an object bigger by stages.
1196 * Extra Fast Growing::          Extra-high-efficiency (though more
1197                                  complicated) growing objects.
1198 * Status of an Obstack::        Inquiries about the status of an obstack.
1199 * Obstacks Data Alignment::     Controlling alignment of objects in obstacks.
1200 * Obstack Chunks::              How obstacks obtain and release chunks;
1201                                  efficiency considerations.
1202 * Summary of Obstacks::
1203 @end menu
1205 @node Creating Obstacks
1206 @subsection Creating Obstacks
1208 The utilities for manipulating obstacks are declared in the header
1209 file @file{obstack.h}.
1210 @pindex obstack.h
1212 @comment obstack.h
1213 @comment GNU
1214 @deftp {Data Type} {struct obstack}
1215 An obstack is represented by a data structure of type @code{struct
1216 obstack}.  This structure has a small fixed size; it records the status
1217 of the obstack and how to find the space in which objects are allocated.
1218 It does not contain any of the objects themselves.  You should not try
1219 to access the contents of the structure directly; use only the functions
1220 described in this chapter.
1221 @end deftp
1223 You can declare variables of type @code{struct obstack} and use them as
1224 obstacks, or you can allocate obstacks dynamically like any other kind
1225 of object.  Dynamic allocation of obstacks allows your program to have a
1226 variable number of different stacks.  (You can even allocate an
1227 obstack structure in another obstack, but this is rarely useful.)
1229 All the functions that work with obstacks require you to specify which
1230 obstack to use.  You do this with a pointer of type @code{struct obstack
1231 *}.  In the following, we often say ``an obstack'' when strictly
1232 speaking the object at hand is such a pointer.
1234 The objects in the obstack are packed into large blocks called
1235 @dfn{chunks}.  The @code{struct obstack} structure points to a chain of
1236 the chunks currently in use.
1238 The obstack library obtains a new chunk whenever you allocate an object
1239 that won't fit in the previous chunk.  Since the obstack library manages
1240 chunks automatically, you don't need to pay much attention to them, but
1241 you do need to supply a function which the obstack library should use to
1242 get a chunk.  Usually you supply a function which uses @code{malloc}
1243 directly or indirectly.  You must also supply a function to free a chunk.
1244 These matters are described in the following section.
1246 @node Preparing for Obstacks
1247 @subsection Preparing for Using Obstacks
1249 Each source file in which you plan to use the obstack functions
1250 must include the header file @file{obstack.h}, like this:
1252 @smallexample
1253 #include <obstack.h>
1254 @end smallexample
1256 @findex obstack_chunk_alloc
1257 @findex obstack_chunk_free
1258 Also, if the source file uses the macro @code{obstack_init}, it must
1259 declare or define two functions or macros that will be called by the
1260 obstack library.  One, @code{obstack_chunk_alloc}, is used to allocate
1261 the chunks of memory into which objects are packed.  The other,
1262 @code{obstack_chunk_free}, is used to return chunks when the objects in
1263 them are freed.  These macros should appear before any use of obstacks
1264 in the source file.
1266 Usually these are defined to use @code{malloc} via the intermediary
1267 @code{xmalloc} (@pxref{Unconstrained Allocation}).  This is done with
1268 the following pair of macro definitions:
1270 @smallexample
1271 #define obstack_chunk_alloc xmalloc
1272 #define obstack_chunk_free free
1273 @end smallexample
1275 @noindent
1276 Though the storage you get using obstacks really comes from @code{malloc},
1277 using obstacks is faster because @code{malloc} is called less often, for
1278 larger blocks of memory.  @xref{Obstack Chunks}, for full details.
1280 At run time, before the program can use a @code{struct obstack} object
1281 as an obstack, it must initialize the obstack by calling
1282 @code{obstack_init}.
1284 @comment obstack.h
1285 @comment GNU
1286 @deftypefun int obstack_init (struct obstack *@var{obstack-ptr})
1287 Initialize obstack @var{obstack-ptr} for allocation of objects.  This
1288 function calls the obstack's @code{obstack_chunk_alloc} function.  If
1289 allocation of memory fails, the function pointed to by
1290 @code{obstack_alloc_failed_handler} is called.  The @code{obstack_init}
1291 function always returns 1 (Compatibility notice: Former versions of
1292 obstack returned 0 if allocation failed).
1293 @end deftypefun
1295 Here are two examples of how to allocate the space for an obstack and
1296 initialize it.  First, an obstack that is a static variable:
1298 @smallexample
1299 static struct obstack myobstack;
1300 @dots{}
1301 obstack_init (&myobstack);
1302 @end smallexample
1304 @noindent
1305 Second, an obstack that is itself dynamically allocated:
1307 @smallexample
1308 struct obstack *myobstack_ptr
1309   = (struct obstack *) xmalloc (sizeof (struct obstack));
1311 obstack_init (myobstack_ptr);
1312 @end smallexample
1314 @comment obstack.h
1315 @comment GNU
1316 @defvar obstack_alloc_failed_handler
1317 The value of this variable is a pointer to a function that
1318 @code{obstack} uses when @code{obstack_chunk_alloc} fails to allocate
1319 memory.  The default action is to print a message and abort.
1320 You should supply a function that either calls @code{exit}
1321 (@pxref{Program Termination}) or @code{longjmp} (@pxref{Non-Local
1322 Exits}) and doesn't return.
1324 @smallexample
1325 void my_obstack_alloc_failed (void)
1326 @dots{}
1327 obstack_alloc_failed_handler = &my_obstack_alloc_failed;
1328 @end smallexample
1330 @end defvar
1332 @node Allocation in an Obstack
1333 @subsection Allocation in an Obstack
1334 @cindex allocation (obstacks)
1336 The most direct way to allocate an object in an obstack is with
1337 @code{obstack_alloc}, which is invoked almost like @code{malloc}.
1339 @comment obstack.h
1340 @comment GNU
1341 @deftypefun {void *} obstack_alloc (struct obstack *@var{obstack-ptr}, int @var{size})
1342 This allocates an uninitialized block of @var{size} bytes in an obstack
1343 and returns its address.  Here @var{obstack-ptr} specifies which obstack
1344 to allocate the block in; it is the address of the @code{struct obstack}
1345 object which represents the obstack.  Each obstack function or macro
1346 requires you to specify an @var{obstack-ptr} as the first argument.
1348 This function calls the obstack's @code{obstack_chunk_alloc} function if
1349 it needs to allocate a new chunk of memory; it calls
1350 @code{obstack_alloc_failed_handler} if allocation of memory by
1351 @code{obstack_chunk_alloc} failed.
1352 @end deftypefun
1354 For example, here is a function that allocates a copy of a string @var{str}
1355 in a specific obstack, which is in the variable @code{string_obstack}:
1357 @smallexample
1358 struct obstack string_obstack;
1360 char *
1361 copystring (char *string)
1363   size_t len = strlen (string) + 1;
1364   char *s = (char *) obstack_alloc (&string_obstack, len);
1365   memcpy (s, string, len);
1366   return s;
1368 @end smallexample
1370 To allocate a block with specified contents, use the function
1371 @code{obstack_copy}, declared like this:
1373 @comment obstack.h
1374 @comment GNU
1375 @deftypefun {void *} obstack_copy (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1376 This allocates a block and initializes it by copying @var{size}
1377 bytes of data starting at @var{address}.  It calls
1378 @code{obstack_alloc_failed_handler} if allocation of memory by
1379 @code{obstack_chunk_alloc} failed.
1380 @end deftypefun
1382 @comment obstack.h
1383 @comment GNU
1384 @deftypefun {void *} obstack_copy0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1385 Like @code{obstack_copy}, but appends an extra byte containing a null
1386 character.  This extra byte is not counted in the argument @var{size}.
1387 @end deftypefun
1389 The @code{obstack_copy0} function is convenient for copying a sequence
1390 of characters into an obstack as a null-terminated string.  Here is an
1391 example of its use:
1393 @smallexample
1394 char *
1395 obstack_savestring (char *addr, int size)
1397   return obstack_copy0 (&myobstack, addr, size);
1399 @end smallexample
1401 @noindent
1402 Contrast this with the previous example of @code{savestring} using
1403 @code{malloc} (@pxref{Basic Allocation}).
1405 @node Freeing Obstack Objects
1406 @subsection Freeing Objects in an Obstack
1407 @cindex freeing (obstacks)
1409 To free an object allocated in an obstack, use the function
1410 @code{obstack_free}.  Since the obstack is a stack of objects, freeing
1411 one object automatically frees all other objects allocated more recently
1412 in the same obstack.
1414 @comment obstack.h
1415 @comment GNU
1416 @deftypefun void obstack_free (struct obstack *@var{obstack-ptr}, void *@var{object})
1417 If @var{object} is a null pointer, everything allocated in the obstack
1418 is freed.  Otherwise, @var{object} must be the address of an object
1419 allocated in the obstack.  Then @var{object} is freed, along with
1420 everything allocated in @var{obstack} since @var{object}.
1421 @end deftypefun
1423 Note that if @var{object} is a null pointer, the result is an
1424 uninitialized obstack.  To free all storage in an obstack but leave it
1425 valid for further allocation, call @code{obstack_free} with the address
1426 of the first object allocated on the obstack:
1428 @smallexample
1429 obstack_free (obstack_ptr, first_object_allocated_ptr);
1430 @end smallexample
1432 Recall that the objects in an obstack are grouped into chunks.  When all
1433 the objects in a chunk become free, the obstack library automatically
1434 frees the chunk (@pxref{Preparing for Obstacks}).  Then other
1435 obstacks, or non-obstack allocation, can reuse the space of the chunk.
1437 @node Obstack Functions
1438 @subsection Obstack Functions and Macros
1439 @cindex macros
1441 The interfaces for using obstacks may be defined either as functions or
1442 as macros, depending on the compiler.  The obstack facility works with
1443 all C compilers, including both @w{ISO C} and traditional C, but there are
1444 precautions you must take if you plan to use compilers other than GNU C.
1446 If you are using an old-fashioned @w{non-ISO C} compiler, all the obstack
1447 ``functions'' are actually defined only as macros.  You can call these
1448 macros like functions, but you cannot use them in any other way (for
1449 example, you cannot take their address).
1451 Calling the macros requires a special precaution: namely, the first
1452 operand (the obstack pointer) may not contain any side effects, because
1453 it may be computed more than once.  For example, if you write this:
1455 @smallexample
1456 obstack_alloc (get_obstack (), 4);
1457 @end smallexample
1459 @noindent
1460 you will find that @code{get_obstack} may be called several times.
1461 If you use @code{*obstack_list_ptr++} as the obstack pointer argument,
1462 you will get very strange results since the incrementation may occur
1463 several times.
1465 In @w{ISO C}, each function has both a macro definition and a function
1466 definition.  The function definition is used if you take the address of the
1467 function without calling it.  An ordinary call uses the macro definition by
1468 default, but you can request the function definition instead by writing the
1469 function name in parentheses, as shown here:
1471 @smallexample
1472 char *x;
1473 void *(*funcp) ();
1474 /* @r{Use the macro}.  */
1475 x = (char *) obstack_alloc (obptr, size);
1476 /* @r{Call the function}.  */
1477 x = (char *) (obstack_alloc) (obptr, size);
1478 /* @r{Take the address of the function}.  */
1479 funcp = obstack_alloc;
1480 @end smallexample
1482 @noindent
1483 This is the same situation that exists in @w{ISO C} for the standard library
1484 functions.  @xref{Macro Definitions}.
1486 @strong{Warning:} When you do use the macros, you must observe the
1487 precaution of avoiding side effects in the first operand, even in @w{ISO C}.
1489 If you use the GNU C compiler, this precaution is not necessary, because
1490 various language extensions in GNU C permit defining the macros so as to
1491 compute each argument only once.
1493 @node Growing Objects
1494 @subsection Growing Objects
1495 @cindex growing objects (in obstacks)
1496 @cindex changing the size of a block (obstacks)
1498 Because storage in obstack chunks is used sequentially, it is possible to
1499 build up an object step by step, adding one or more bytes at a time to the
1500 end of the object.  With this technique, you do not need to know how much
1501 data you will put in the object until you come to the end of it.  We call
1502 this the technique of @dfn{growing objects}.  The special functions
1503 for adding data to the growing object are described in this section.
1505 You don't need to do anything special when you start to grow an object.
1506 Using one of the functions to add data to the object automatically
1507 starts it.  However, it is necessary to say explicitly when the object is
1508 finished.  This is done with the function @code{obstack_finish}.
1510 The actual address of the object thus built up is not known until the
1511 object is finished.  Until then, it always remains possible that you will
1512 add so much data that the object must be copied into a new chunk.
1514 While the obstack is in use for a growing object, you cannot use it for
1515 ordinary allocation of another object.  If you try to do so, the space
1516 already added to the growing object will become part of the other object.
1518 @comment obstack.h
1519 @comment GNU
1520 @deftypefun void obstack_blank (struct obstack *@var{obstack-ptr}, int @var{size})
1521 The most basic function for adding to a growing object is
1522 @code{obstack_blank}, which adds space without initializing it.
1523 @end deftypefun
1525 @comment obstack.h
1526 @comment GNU
1527 @deftypefun void obstack_grow (struct obstack *@var{obstack-ptr}, void *@var{data}, int @var{size})
1528 To add a block of initialized space, use @code{obstack_grow}, which is
1529 the growing-object analogue of @code{obstack_copy}.  It adds @var{size}
1530 bytes of data to the growing object, copying the contents from
1531 @var{data}.
1532 @end deftypefun
1534 @comment obstack.h
1535 @comment GNU
1536 @deftypefun void obstack_grow0 (struct obstack *@var{obstack-ptr}, void *@var{data}, int @var{size})
1537 This is the growing-object analogue of @code{obstack_copy0}.  It adds
1538 @var{size} bytes copied from @var{data}, followed by an additional null
1539 character.
1540 @end deftypefun
1542 @comment obstack.h
1543 @comment GNU
1544 @deftypefun void obstack_1grow (struct obstack *@var{obstack-ptr}, char @var{c})
1545 To add one character at a time, use the function @code{obstack_1grow}.
1546 It adds a single byte containing @var{c} to the growing object.
1547 @end deftypefun
1549 @comment obstack.h
1550 @comment GNU
1551 @deftypefun void obstack_ptr_grow (struct obstack *@var{obstack-ptr}, void *@var{data})
1552 Adding the value of a pointer one can use the function
1553 @code{obstack_ptr_grow}.  It adds @code{sizeof (void *)} bytes
1554 containing the value of @var{data}.
1555 @end deftypefun
1557 @comment obstack.h
1558 @comment GNU
1559 @deftypefun void obstack_int_grow (struct obstack *@var{obstack-ptr}, int @var{data})
1560 A single value of type @code{int} can be added by using the
1561 @code{obstack_int_grow} function.  It adds @code{sizeof (int)} bytes to
1562 the growing object and initializes them with the value of @var{data}.
1563 @end deftypefun
1565 @comment obstack.h
1566 @comment GNU
1567 @deftypefun {void *} obstack_finish (struct obstack *@var{obstack-ptr})
1568 When you are finished growing the object, use the function
1569 @code{obstack_finish} to close it off and return its final address.
1571 Once you have finished the object, the obstack is available for ordinary
1572 allocation or for growing another object.
1574 This function can return a null pointer under the same conditions as
1575 @code{obstack_alloc} (@pxref{Allocation in an Obstack}).
1576 @end deftypefun
1578 When you build an object by growing it, you will probably need to know
1579 afterward how long it became.  You need not keep track of this as you grow
1580 the object, because you can find out the length from the obstack just
1581 before finishing the object with the function @code{obstack_object_size},
1582 declared as follows:
1584 @comment obstack.h
1585 @comment GNU
1586 @deftypefun int obstack_object_size (struct obstack *@var{obstack-ptr})
1587 This function returns the current size of the growing object, in bytes.
1588 Remember to call this function @emph{before} finishing the object.
1589 After it is finished, @code{obstack_object_size} will return zero.
1590 @end deftypefun
1592 If you have started growing an object and wish to cancel it, you should
1593 finish it and then free it, like this:
1595 @smallexample
1596 obstack_free (obstack_ptr, obstack_finish (obstack_ptr));
1597 @end smallexample
1599 @noindent
1600 This has no effect if no object was growing.
1602 @cindex shrinking objects
1603 You can use @code{obstack_blank} with a negative size argument to make
1604 the current object smaller.  Just don't try to shrink it beyond zero
1605 length---there's no telling what will happen if you do that.
1607 @node Extra Fast Growing
1608 @subsection Extra Fast Growing Objects
1609 @cindex efficiency and obstacks
1611 The usual functions for growing objects incur overhead for checking
1612 whether there is room for the new growth in the current chunk.  If you
1613 are frequently constructing objects in small steps of growth, this
1614 overhead can be significant.
1616 You can reduce the overhead by using special ``fast growth''
1617 functions that grow the object without checking.  In order to have a
1618 robust program, you must do the checking yourself.  If you do this checking
1619 in the simplest way each time you are about to add data to the object, you
1620 have not saved anything, because that is what the ordinary growth
1621 functions do.  But if you can arrange to check less often, or check
1622 more efficiently, then you make the program faster.
1624 The function @code{obstack_room} returns the amount of room available
1625 in the current chunk.  It is declared as follows:
1627 @comment obstack.h
1628 @comment GNU
1629 @deftypefun int obstack_room (struct obstack *@var{obstack-ptr})
1630 This returns the number of bytes that can be added safely to the current
1631 growing object (or to an object about to be started) in obstack
1632 @var{obstack} using the fast growth functions.
1633 @end deftypefun
1635 While you know there is room, you can use these fast growth functions
1636 for adding data to a growing object:
1638 @comment obstack.h
1639 @comment GNU
1640 @deftypefun void obstack_1grow_fast (struct obstack *@var{obstack-ptr}, char @var{c})
1641 The function @code{obstack_1grow_fast} adds one byte containing the
1642 character @var{c} to the growing object in obstack @var{obstack-ptr}.
1643 @end deftypefun
1645 @comment obstack.h
1646 @comment GNU
1647 @deftypefun void obstack_ptr_grow_fast (struct obstack *@var{obstack-ptr}, void *@var{data})
1648 The function @code{obstack_ptr_grow_fast} adds @code{sizeof (void *)}
1649 bytes containing the value of @var{data} to the growing object in
1650 obstack @var{obstack-ptr}.
1651 @end deftypefun
1653 @comment obstack.h
1654 @comment GNU
1655 @deftypefun void obstack_int_grow_fast (struct obstack *@var{obstack-ptr}, int @var{data})
1656 The function @code{obstack_int_grow_fast} adds @code{sizeof (int)} bytes
1657 containing the value of @var{data} to the growing object in obstack
1658 @var{obstack-ptr}.
1659 @end deftypefun
1661 @comment obstack.h
1662 @comment GNU
1663 @deftypefun void obstack_blank_fast (struct obstack *@var{obstack-ptr}, int @var{size})
1664 The function @code{obstack_blank_fast} adds @var{size} bytes to the
1665 growing object in obstack @var{obstack-ptr} without initializing them.
1666 @end deftypefun
1668 When you check for space using @code{obstack_room} and there is not
1669 enough room for what you want to add, the fast growth functions
1670 are not safe.  In this case, simply use the corresponding ordinary
1671 growth function instead.  Very soon this will copy the object to a
1672 new chunk; then there will be lots of room available again.
1674 So, each time you use an ordinary growth function, check afterward for
1675 sufficient space using @code{obstack_room}.  Once the object is copied
1676 to a new chunk, there will be plenty of space again, so the program will
1677 start using the fast growth functions again.
1679 Here is an example:
1681 @smallexample
1682 @group
1683 void
1684 add_string (struct obstack *obstack, const char *ptr, int len)
1686   while (len > 0)
1687     @{
1688       int room = obstack_room (obstack);
1689       if (room == 0)
1690         @{
1691           /* @r{Not enough room. Add one character slowly,}
1692              @r{which may copy to a new chunk and make room.}  */
1693           obstack_1grow (obstack, *ptr++);
1694           len--;
1695         @}
1696       else
1697         @{
1698           if (room > len)
1699             room = len;
1700           /* @r{Add fast as much as we have room for.} */
1701           len -= room;
1702           while (room-- > 0)
1703             obstack_1grow_fast (obstack, *ptr++);
1704         @}
1705     @}
1707 @end group
1708 @end smallexample
1710 @node Status of an Obstack
1711 @subsection Status of an Obstack
1712 @cindex obstack status
1713 @cindex status of obstack
1715 Here are functions that provide information on the current status of
1716 allocation in an obstack.  You can use them to learn about an object while
1717 still growing it.
1719 @comment obstack.h
1720 @comment GNU
1721 @deftypefun {void *} obstack_base (struct obstack *@var{obstack-ptr})
1722 This function returns the tentative address of the beginning of the
1723 currently growing object in @var{obstack-ptr}.  If you finish the object
1724 immediately, it will have that address.  If you make it larger first, it
1725 may outgrow the current chunk---then its address will change!
1727 If no object is growing, this value says where the next object you
1728 allocate will start (once again assuming it fits in the current
1729 chunk).
1730 @end deftypefun
1732 @comment obstack.h
1733 @comment GNU
1734 @deftypefun {void *} obstack_next_free (struct obstack *@var{obstack-ptr})
1735 This function returns the address of the first free byte in the current
1736 chunk of obstack @var{obstack-ptr}.  This is the end of the currently
1737 growing object.  If no object is growing, @code{obstack_next_free}
1738 returns the same value as @code{obstack_base}.
1739 @end deftypefun
1741 @comment obstack.h
1742 @comment GNU
1743 @deftypefun int obstack_object_size (struct obstack *@var{obstack-ptr})
1744 This function returns the size in bytes of the currently growing object.
1745 This is equivalent to
1747 @smallexample
1748 obstack_next_free (@var{obstack-ptr}) - obstack_base (@var{obstack-ptr})
1749 @end smallexample
1750 @end deftypefun
1752 @node Obstacks Data Alignment
1753 @subsection Alignment of Data in Obstacks
1754 @cindex alignment (in obstacks)
1756 Each obstack has an @dfn{alignment boundary}; each object allocated in
1757 the obstack automatically starts on an address that is a multiple of the
1758 specified boundary.  By default, this boundary is 4 bytes.
1760 To access an obstack's alignment boundary, use the macro
1761 @code{obstack_alignment_mask}, whose function prototype looks like
1762 this:
1764 @comment obstack.h
1765 @comment GNU
1766 @deftypefn Macro int obstack_alignment_mask (struct obstack *@var{obstack-ptr})
1767 The value is a bit mask; a bit that is 1 indicates that the corresponding
1768 bit in the address of an object should be 0.  The mask value should be one
1769 less than a power of 2; the effect is that all object addresses are
1770 multiples of that power of 2.  The default value of the mask is 3, so that
1771 addresses are multiples of 4.  A mask value of 0 means an object can start
1772 on any multiple of 1 (that is, no alignment is required).
1774 The expansion of the macro @code{obstack_alignment_mask} is an lvalue,
1775 so you can alter the mask by assignment.  For example, this statement:
1777 @smallexample
1778 obstack_alignment_mask (obstack_ptr) = 0;
1779 @end smallexample
1781 @noindent
1782 has the effect of turning off alignment processing in the specified obstack.
1783 @end deftypefn
1785 Note that a change in alignment mask does not take effect until
1786 @emph{after} the next time an object is allocated or finished in the
1787 obstack.  If you are not growing an object, you can make the new
1788 alignment mask take effect immediately by calling @code{obstack_finish}.
1789 This will finish a zero-length object and then do proper alignment for
1790 the next object.
1792 @node Obstack Chunks
1793 @subsection Obstack Chunks
1794 @cindex efficiency of chunks
1795 @cindex chunks
1797 Obstacks work by allocating space for themselves in large chunks, and
1798 then parceling out space in the chunks to satisfy your requests.  Chunks
1799 are normally 4096 bytes long unless you specify a different chunk size.
1800 The chunk size includes 8 bytes of overhead that are not actually used
1801 for storing objects.  Regardless of the specified size, longer chunks
1802 will be allocated when necessary for long objects.
1804 The obstack library allocates chunks by calling the function
1805 @code{obstack_chunk_alloc}, which you must define.  When a chunk is no
1806 longer needed because you have freed all the objects in it, the obstack
1807 library frees the chunk by calling @code{obstack_chunk_free}, which you
1808 must also define.
1810 These two must be defined (as macros) or declared (as functions) in each
1811 source file that uses @code{obstack_init} (@pxref{Creating Obstacks}).
1812 Most often they are defined as macros like this:
1814 @smallexample
1815 #define obstack_chunk_alloc malloc
1816 #define obstack_chunk_free free
1817 @end smallexample
1819 Note that these are simple macros (no arguments).  Macro definitions with
1820 arguments will not work!  It is necessary that @code{obstack_chunk_alloc}
1821 or @code{obstack_chunk_free}, alone, expand into a function name if it is
1822 not itself a function name.
1824 If you allocate chunks with @code{malloc}, the chunk size should be a
1825 power of 2.  The default chunk size, 4096, was chosen because it is long
1826 enough to satisfy many typical requests on the obstack yet short enough
1827 not to waste too much memory in the portion of the last chunk not yet used.
1829 @comment obstack.h
1830 @comment GNU
1831 @deftypefn Macro int obstack_chunk_size (struct obstack *@var{obstack-ptr})
1832 This returns the chunk size of the given obstack.
1833 @end deftypefn
1835 Since this macro expands to an lvalue, you can specify a new chunk size by
1836 assigning it a new value.  Doing so does not affect the chunks already
1837 allocated, but will change the size of chunks allocated for that particular
1838 obstack in the future.  It is unlikely to be useful to make the chunk size
1839 smaller, but making it larger might improve efficiency if you are
1840 allocating many objects whose size is comparable to the chunk size.  Here
1841 is how to do so cleanly:
1843 @smallexample
1844 if (obstack_chunk_size (obstack_ptr) < @var{new-chunk-size})
1845   obstack_chunk_size (obstack_ptr) = @var{new-chunk-size};
1846 @end smallexample
1848 @node Summary of Obstacks
1849 @subsection Summary of Obstack Functions
1851 Here is a summary of all the functions associated with obstacks.  Each
1852 takes the address of an obstack (@code{struct obstack *}) as its first
1853 argument.
1855 @table @code
1856 @item void obstack_init (struct obstack *@var{obstack-ptr})
1857 Initialize use of an obstack.  @xref{Creating Obstacks}.
1859 @item void *obstack_alloc (struct obstack *@var{obstack-ptr}, int @var{size})
1860 Allocate an object of @var{size} uninitialized bytes.
1861 @xref{Allocation in an Obstack}.
1863 @item void *obstack_copy (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1864 Allocate an object of @var{size} bytes, with contents copied from
1865 @var{address}.  @xref{Allocation in an Obstack}.
1867 @item void *obstack_copy0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1868 Allocate an object of @var{size}+1 bytes, with @var{size} of them copied
1869 from @var{address}, followed by a null character at the end.
1870 @xref{Allocation in an Obstack}.
1872 @item void obstack_free (struct obstack *@var{obstack-ptr}, void *@var{object})
1873 Free @var{object} (and everything allocated in the specified obstack
1874 more recently than @var{object}).  @xref{Freeing Obstack Objects}.
1876 @item void obstack_blank (struct obstack *@var{obstack-ptr}, int @var{size})
1877 Add @var{size} uninitialized bytes to a growing object.
1878 @xref{Growing Objects}.
1880 @item void obstack_grow (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1881 Add @var{size} bytes, copied from @var{address}, to a growing object.
1882 @xref{Growing Objects}.
1884 @item void obstack_grow0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1885 Add @var{size} bytes, copied from @var{address}, to a growing object,
1886 and then add another byte containing a null character.  @xref{Growing
1887 Objects}.
1889 @item void obstack_1grow (struct obstack *@var{obstack-ptr}, char @var{data-char})
1890 Add one byte containing @var{data-char} to a growing object.
1891 @xref{Growing Objects}.
1893 @item void *obstack_finish (struct obstack *@var{obstack-ptr})
1894 Finalize the object that is growing and return its permanent address.
1895 @xref{Growing Objects}.
1897 @item int obstack_object_size (struct obstack *@var{obstack-ptr})
1898 Get the current size of the currently growing object.  @xref{Growing
1899 Objects}.
1901 @item void obstack_blank_fast (struct obstack *@var{obstack-ptr}, int @var{size})
1902 Add @var{size} uninitialized bytes to a growing object without checking
1903 that there is enough room.  @xref{Extra Fast Growing}.
1905 @item void obstack_1grow_fast (struct obstack *@var{obstack-ptr}, char @var{data-char})
1906 Add one byte containing @var{data-char} to a growing object without
1907 checking that there is enough room.  @xref{Extra Fast Growing}.
1909 @item int obstack_room (struct obstack *@var{obstack-ptr})
1910 Get the amount of room now available for growing the current object.
1911 @xref{Extra Fast Growing}.
1913 @item int obstack_alignment_mask (struct obstack *@var{obstack-ptr})
1914 The mask used for aligning the beginning of an object.  This is an
1915 lvalue.  @xref{Obstacks Data Alignment}.
1917 @item int obstack_chunk_size (struct obstack *@var{obstack-ptr})
1918 The size for allocating chunks.  This is an lvalue.  @xref{Obstack Chunks}.
1920 @item void *obstack_base (struct obstack *@var{obstack-ptr})
1921 Tentative starting address of the currently growing object.
1922 @xref{Status of an Obstack}.
1924 @item void *obstack_next_free (struct obstack *@var{obstack-ptr})
1925 Address just after the end of the currently growing object.
1926 @xref{Status of an Obstack}.
1927 @end table
1929 @node Variable Size Automatic
1930 @section Automatic Storage with Variable Size
1931 @cindex automatic freeing
1932 @cindex @code{alloca} function
1933 @cindex automatic storage with variable size
1935 The function @code{alloca} supports a kind of half-dynamic allocation in
1936 which blocks are allocated dynamically but freed automatically.
1938 Allocating a block with @code{alloca} is an explicit action; you can
1939 allocate as many blocks as you wish, and compute the size at run time.  But
1940 all the blocks are freed when you exit the function that @code{alloca} was
1941 called from, just as if they were automatic variables declared in that
1942 function.  There is no way to free the space explicitly.
1944 The prototype for @code{alloca} is in @file{stdlib.h}.  This function is
1945 a BSD extension.
1946 @pindex stdlib.h
1948 @comment stdlib.h
1949 @comment GNU, BSD
1950 @deftypefun {void *} alloca (size_t @var{size});
1951 The return value of @code{alloca} is the address of a block of @var{size}
1952 bytes of storage, allocated in the stack frame of the calling function.
1953 @end deftypefun
1955 Do not use @code{alloca} inside the arguments of a function call---you
1956 will get unpredictable results, because the stack space for the
1957 @code{alloca} would appear on the stack in the middle of the space for
1958 the function arguments.  An example of what to avoid is @code{foo (x,
1959 alloca (4), y)}.
1960 @c This might get fixed in future versions of GCC, but that won't make
1961 @c it safe with compilers generally.
1963 @menu
1964 * Alloca Example::              Example of using @code{alloca}.
1965 * Advantages of Alloca::        Reasons to use @code{alloca}.
1966 * Disadvantages of Alloca::     Reasons to avoid @code{alloca}.
1967 * GNU C Variable-Size Arrays::  Only in GNU C, here is an alternative
1968                                  method of allocating dynamically and
1969                                  freeing automatically.
1970 @end menu
1972 @node Alloca Example
1973 @subsection @code{alloca} Example
1975 As an example of use of @code{alloca}, here is a function that opens a file
1976 name made from concatenating two argument strings, and returns a file
1977 descriptor or minus one signifying failure:
1979 @smallexample
1981 open2 (char *str1, char *str2, int flags, int mode)
1983   char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
1984   stpcpy (stpcpy (name, str1), str2);
1985   return open (name, flags, mode);
1987 @end smallexample
1989 @noindent
1990 Here is how you would get the same results with @code{malloc} and
1991 @code{free}:
1993 @smallexample
1995 open2 (char *str1, char *str2, int flags, int mode)
1997   char *name = (char *) malloc (strlen (str1) + strlen (str2) + 1);
1998   int desc;
1999   if (name == 0)
2000     fatal ("virtual memory exceeded");
2001   stpcpy (stpcpy (name, str1), str2);
2002   desc = open (name, flags, mode);
2003   free (name);
2004   return desc;
2006 @end smallexample
2008 As you can see, it is simpler with @code{alloca}.  But @code{alloca} has
2009 other, more important advantages, and some disadvantages.
2011 @node Advantages of Alloca
2012 @subsection Advantages of @code{alloca}
2014 Here are the reasons why @code{alloca} may be preferable to @code{malloc}:
2016 @itemize @bullet
2017 @item
2018 Using @code{alloca} wastes very little space and is very fast.  (It is
2019 open-coded by the GNU C compiler.)
2021 @item
2022 Since @code{alloca} does not have separate pools for different sizes of
2023 block, space used for any size block can be reused for any other size.
2024 @code{alloca} does not cause storage fragmentation.
2026 @item
2027 @cindex longjmp
2028 Nonlocal exits done with @code{longjmp} (@pxref{Non-Local Exits})
2029 automatically free the space allocated with @code{alloca} when they exit
2030 through the function that called @code{alloca}.  This is the most
2031 important reason to use @code{alloca}.
2033 To illustrate this, suppose you have a function
2034 @code{open_or_report_error} which returns a descriptor, like
2035 @code{open}, if it succeeds, but does not return to its caller if it
2036 fails.  If the file cannot be opened, it prints an error message and
2037 jumps out to the command level of your program using @code{longjmp}.
2038 Let's change @code{open2} (@pxref{Alloca Example}) to use this
2039 subroutine:@refill
2041 @smallexample
2043 open2 (char *str1, char *str2, int flags, int mode)
2045   char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
2046   stpcpy (stpcpy (name, str1), str2);
2047   return open_or_report_error (name, flags, mode);
2049 @end smallexample
2051 @noindent
2052 Because of the way @code{alloca} works, the storage it allocates is
2053 freed even when an error occurs, with no special effort required.
2055 By contrast, the previous definition of @code{open2} (which uses
2056 @code{malloc} and @code{free}) would develop a storage leak if it were
2057 changed in this way.  Even if you are willing to make more changes to
2058 fix it, there is no easy way to do so.
2059 @end itemize
2061 @node Disadvantages of Alloca
2062 @subsection Disadvantages of @code{alloca}
2064 @cindex @code{alloca} disadvantages
2065 @cindex disadvantages of @code{alloca}
2066 These are the disadvantages of @code{alloca} in comparison with
2067 @code{malloc}:
2069 @itemize @bullet
2070 @item
2071 If you try to allocate more storage than the machine can provide, you
2072 don't get a clean error message.  Instead you get a fatal signal like
2073 the one you would get from an infinite recursion; probably a
2074 segmentation violation (@pxref{Program Error Signals}).
2076 @item
2077 Some non-GNU systems fail to support @code{alloca}, so it is less
2078 portable.  However, a slower emulation of @code{alloca} written in C
2079 is available for use on systems with this deficiency.
2080 @end itemize
2082 @node GNU C Variable-Size Arrays
2083 @subsection GNU C Variable-Size Arrays
2084 @cindex variable-sized arrays
2086 In GNU C, you can replace most uses of @code{alloca} with an array of
2087 variable size.  Here is how @code{open2} would look then:
2089 @smallexample
2090 int open2 (char *str1, char *str2, int flags, int mode)
2092   char name[strlen (str1) + strlen (str2) + 1];
2093   stpcpy (stpcpy (name, str1), str2);
2094   return open (name, flags, mode);
2096 @end smallexample
2098 But @code{alloca} is not always equivalent to a variable-sized array, for
2099 several reasons:
2101 @itemize @bullet
2102 @item
2103 A variable size array's space is freed at the end of the scope of the
2104 name of the array.  The space allocated with @code{alloca}
2105 remains until the end of the function.
2107 @item
2108 It is possible to use @code{alloca} within a loop, allocating an
2109 additional block on each iteration.  This is impossible with
2110 variable-sized arrays.
2111 @end itemize
2113 @strong{Note:} If you mix use of @code{alloca} and variable-sized arrays
2114 within one function, exiting a scope in which a variable-sized array was
2115 declared frees all blocks allocated with @code{alloca} during the
2116 execution of that scope.
2118 @ignore
2119 @c This was never actually implemented.  -zw
2120 @node Relocating Allocator
2121 @section Relocating Allocator
2123 @cindex relocating memory allocator
2124 Any system of dynamic memory allocation has overhead: the amount of
2125 space it uses is more than the amount the program asks for.  The
2126 @dfn{relocating memory allocator} achieves very low overhead by moving
2127 blocks in memory as necessary, on its own initiative.
2129 @c @menu
2130 @c * Relocator Concepts::               How to understand relocating allocation.
2131 @c * Using Relocator::          Functions for relocating allocation.
2132 @c @end menu
2134 @node Relocator Concepts
2135 @subsection Concepts of Relocating Allocation
2137 @ifinfo
2138 The @dfn{relocating memory allocator} achieves very low overhead by
2139 moving blocks in memory as necessary, on its own initiative.
2140 @end ifinfo
2142 When you allocate a block with @code{malloc}, the address of the block
2143 never changes unless you use @code{realloc} to change its size.  Thus,
2144 you can safely store the address in various places, temporarily or
2145 permanently, as you like.  This is not safe when you use the relocating
2146 memory allocator, because any and all relocatable blocks can move
2147 whenever you allocate memory in any fashion.  Even calling @code{malloc}
2148 or @code{realloc} can move the relocatable blocks.
2150 @cindex handle
2151 For each relocatable block, you must make a @dfn{handle}---a pointer
2152 object in memory, designated to store the address of that block.  The
2153 relocating allocator knows where each block's handle is, and updates the
2154 address stored there whenever it moves the block, so that the handle
2155 always points to the block.  Each time you access the contents of the
2156 block, you should fetch its address anew from the handle.
2158 To call any of the relocating allocator functions from a signal handler
2159 is almost certainly incorrect, because the signal could happen at any
2160 time and relocate all the blocks.  The only way to make this safe is to
2161 block the signal around any access to the contents of any relocatable
2162 block---not a convenient mode of operation.  @xref{Nonreentrancy}.
2164 @node Using Relocator
2165 @subsection Allocating and Freeing Relocatable Blocks
2167 @pindex malloc.h
2168 In the descriptions below, @var{handleptr} designates the address of the
2169 handle.  All the functions are declared in @file{malloc.h}; all are GNU
2170 extensions.
2172 @comment malloc.h
2173 @comment GNU
2174 @c @deftypefun {void *} r_alloc (void **@var{handleptr}, size_t @var{size})
2175 This function allocates a relocatable block of size @var{size}.  It
2176 stores the block's address in @code{*@var{handleptr}} and returns
2177 a non-null pointer to indicate success.
2179 If @code{r_alloc} can't get the space needed, it stores a null pointer
2180 in @code{*@var{handleptr}}, and returns a null pointer.
2181 @end deftypefun
2183 @comment malloc.h
2184 @comment GNU
2185 @c @deftypefun void r_alloc_free (void **@var{handleptr})
2186 This function is the way to free a relocatable block.  It frees the
2187 block that @code{*@var{handleptr}} points to, and stores a null pointer
2188 in @code{*@var{handleptr}} to show it doesn't point to an allocated
2189 block any more.
2190 @end deftypefun
2192 @comment malloc.h
2193 @comment GNU
2194 @c @deftypefun {void *} r_re_alloc (void **@var{handleptr}, size_t @var{size})
2195 The function @code{r_re_alloc} adjusts the size of the block that
2196 @code{*@var{handleptr}} points to, making it @var{size} bytes long.  It
2197 stores the address of the resized block in @code{*@var{handleptr}} and
2198 returns a non-null pointer to indicate success.
2200 If enough memory is not available, this function returns a null pointer
2201 and does not modify @code{*@var{handleptr}}.
2202 @end deftypefun
2203 @end ignore
2205 @ignore
2206 @comment No longer available...
2208 @comment @node Memory Warnings
2209 @comment @section Memory Usage Warnings
2210 @comment @cindex memory usage warnings
2211 @comment @cindex warnings of memory almost full
2213 @pindex malloc.c
2214 You can ask for warnings as the program approaches running out of memory
2215 space, by calling @code{memory_warnings}.  This tells @code{malloc} to
2216 check memory usage every time it asks for more memory from the operating
2217 system.  This is a GNU extension declared in @file{malloc.h}.
2219 @comment malloc.h
2220 @comment GNU
2221 @comment @deftypefun void memory_warnings (void *@var{start}, void (*@var{warn-func}) (const char *))
2222 Call this function to request warnings for nearing exhaustion of virtual
2223 memory.
2225 The argument @var{start} says where data space begins, in memory.  The
2226 allocator compares this against the last address used and against the
2227 limit of data space, to determine the fraction of available memory in
2228 use.  If you supply zero for @var{start}, then a default value is used
2229 which is right in most circumstances.
2231 For @var{warn-func}, supply a function that @code{malloc} can call to
2232 warn you.  It is called with a string (a warning message) as argument.
2233 Normally it ought to display the string for the user to read.
2234 @end deftypefun
2236 The warnings come when memory becomes 75% full, when it becomes 85%
2237 full, and when it becomes 95% full.  Above 95% you get another warning
2238 each time memory usage increases.
2240 @end ignore