Update.
[glibc.git] / manual / memory.texi
blobd55a4d4fc34414a7f4bec06594bd7e6e539b5265
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   memcpy (value, ptr, len);
234   value[len] = '\0';
235   return value;
237 @end group
238 @end smallexample
240 The block that @code{malloc} gives you is guaranteed to be aligned so
241 that it can hold any type of data.  In the GNU system, the address is
242 always a multiple of eight on most systems, and a multiple of 16 on
243 64-bit systems.  Only rarely is any higher boundary (such as a page
244 boundary) necessary; for those cases, use @code{memalign} or
245 @code{valloc} (@pxref{Aligned Memory Blocks}).
247 Note that the memory located after the end of the block is likely to be
248 in use for something else; perhaps a block already allocated by another
249 call to @code{malloc}.  If you attempt to treat the block as longer than
250 you asked for it to be, you are liable to destroy the data that
251 @code{malloc} uses to keep track of its blocks, or you may destroy the
252 contents of another block.  If you have already allocated a block and
253 discover you want it to be bigger, use @code{realloc} (@pxref{Changing
254 Block Size}).
256 @node Freeing after Malloc
257 @subsection Freeing Memory Allocated with @code{malloc}
258 @cindex freeing memory allocated with @code{malloc}
259 @cindex heap, freeing memory from
261 When you no longer need a block that you got with @code{malloc}, use the
262 function @code{free} to make the block available to be allocated again.
263 The prototype for this function is in @file{stdlib.h}.
264 @pindex stdlib.h
266 @comment malloc.h stdlib.h
267 @comment ISO
268 @deftypefun void free (void *@var{ptr})
269 The @code{free} function deallocates the block of storage pointed at
270 by @var{ptr}.
271 @end deftypefun
273 @comment stdlib.h
274 @comment Sun
275 @deftypefun void cfree (void *@var{ptr})
276 This function does the same thing as @code{free}.  It's provided for
277 backward compatibility with SunOS; you should use @code{free} instead.
278 @end deftypefun
280 Freeing a block alters the contents of the block.  @strong{Do not expect to
281 find any data (such as a pointer to the next block in a chain of blocks) in
282 the block after freeing it.}  Copy whatever you need out of the block before
283 freeing it!  Here is an example of the proper way to free all the blocks in
284 a chain, and the strings that they point to:
286 @smallexample
287 struct chain
288   @{
289     struct chain *next;
290     char *name;
291   @}
293 void
294 free_chain (struct chain *chain)
296   while (chain != 0)
297     @{
298       struct chain *next = chain->next;
299       free (chain->name);
300       free (chain);
301       chain = next;
302     @}
304 @end smallexample
306 Occasionally, @code{free} can actually return memory to the operating
307 system and make the process smaller.  Usually, all it can do is allow a
308 later call to @code{malloc} to reuse the space.  In the meantime, the
309 space remains in your program as part of a free-list used internally by
310 @code{malloc}.
312 There is no point in freeing blocks at the end of a program, because all
313 of the program's space is given back to the system when the process
314 terminates.
316 @node Changing Block Size
317 @subsection Changing the Size of a Block
318 @cindex changing the size of a block (@code{malloc})
320 Often you do not know for certain how big a block you will ultimately need
321 at the time you must begin to use the block.  For example, the block might
322 be a buffer that you use to hold a line being read from a file; no matter
323 how long you make the buffer initially, you may encounter a line that is
324 longer.
326 You can make the block longer by calling @code{realloc}.  This function
327 is declared in @file{stdlib.h}.
328 @pindex stdlib.h
330 @comment malloc.h stdlib.h
331 @comment ISO
332 @deftypefun {void *} realloc (void *@var{ptr}, size_t @var{newsize})
333 The @code{realloc} function changes the size of the block whose address is
334 @var{ptr} to be @var{newsize}.
336 Since the space after the end of the block may be in use, @code{realloc}
337 may find it necessary to copy the block to a new address where more free
338 space is available.  The value of @code{realloc} is the new address of the
339 block.  If the block needs to be moved, @code{realloc} copies the old
340 contents.
342 If you pass a null pointer for @var{ptr}, @code{realloc} behaves just
343 like @samp{malloc (@var{newsize})}.  This can be convenient, but beware
344 that older implementations (before @w{ISO C}) may not support this
345 behavior, and will probably crash when @code{realloc} is passed a null
346 pointer.
347 @end deftypefun
349 Like @code{malloc}, @code{realloc} may return a null pointer if no
350 memory space is available to make the block bigger.  When this happens,
351 the original block is untouched; it has not been modified or relocated.
353 In most cases it makes no difference what happens to the original block
354 when @code{realloc} fails, because the application program cannot continue
355 when it is out of memory, and the only thing to do is to give a fatal error
356 message.  Often it is convenient to write and use a subroutine,
357 conventionally called @code{xrealloc}, that takes care of the error message
358 as @code{xmalloc} does for @code{malloc}:
360 @smallexample
361 void *
362 xrealloc (void *ptr, size_t size)
364   register void *value = realloc (ptr, size);
365   if (value == 0)
366     fatal ("Virtual memory exhausted");
367   return value;
369 @end smallexample
371 You can also use @code{realloc} to make a block smaller.  The reason you
372 would do this is to avoid tying up a lot of memory space when only a little
373 is needed.
374 @comment The following is no longer true with the new malloc.
375 @comment But it seems wise to keep the warning for other implementations.
376 In several allocation implementations, making a block smaller sometimes
377 necessitates copying it, so it can fail if no other space is available.
379 If the new size you specify is the same as the old size, @code{realloc}
380 is guaranteed to change nothing and return the same address that you gave.
382 @node Allocating Cleared Space
383 @subsection Allocating Cleared Space
385 The function @code{calloc} allocates memory and clears it to zero.  It
386 is declared in @file{stdlib.h}.
387 @pindex stdlib.h
389 @comment malloc.h stdlib.h
390 @comment ISO
391 @deftypefun {void *} calloc (size_t @var{count}, size_t @var{eltsize})
392 This function allocates a block long enough to contain a vector of
393 @var{count} elements, each of size @var{eltsize}.  Its contents are
394 cleared to zero before @code{calloc} returns.
395 @end deftypefun
397 You could define @code{calloc} as follows:
399 @smallexample
400 void *
401 calloc (size_t count, size_t eltsize)
403   size_t size = count * eltsize;
404   void *value = malloc (size);
405   if (value != 0)
406     memset (value, 0, size);
407   return value;
409 @end smallexample
411 But in general, it is not guaranteed that @code{calloc} calls
412 @code{malloc} internally.  Therefore, if an application provides its own
413 @code{malloc}/@code{realloc}/@code{free} outside the C library, it
414 should always define @code{calloc}, too.
416 @node Efficiency and Malloc
417 @subsection Efficiency Considerations for @code{malloc}
418 @cindex efficiency and @code{malloc}
420 @ignore
422 @c No longer true, see below instead.
423 To make the best use of @code{malloc}, it helps to know that the GNU
424 version of @code{malloc} always dispenses small amounts of memory in
425 blocks whose sizes are powers of two.  It keeps separate pools for each
426 power of two.  This holds for sizes up to a page size.  Therefore, if
427 you are free to choose the size of a small block in order to make
428 @code{malloc} more efficient, make it a power of two.
429 @c !!! xref getpagesize
431 Once a page is split up for a particular block size, it can't be reused
432 for another size unless all the blocks in it are freed.  In many
433 programs, this is unlikely to happen.  Thus, you can sometimes make a
434 program use memory more efficiently by using blocks of the same size for
435 many different purposes.
437 When you ask for memory blocks of a page or larger, @code{malloc} uses a
438 different strategy; it rounds the size up to a multiple of a page, and
439 it can coalesce and split blocks as needed.
441 The reason for the two strategies is that it is important to allocate
442 and free small blocks as fast as possible, but speed is less important
443 for a large block since the program normally spends a fair amount of
444 time using it.  Also, large blocks are normally fewer in number.
445 Therefore, for large blocks, it makes sense to use a method which takes
446 more time to minimize the wasted space.
448 @end ignore
450 As apposed to other versions, the @code{malloc} in GNU libc does not
451 round up block sizes to powers of two, neither for large nor for small
452 sizes.  Neighboring chunks can be coalesced on a @code{free} no matter
453 what their size is.  This makes the implementation suitable for all
454 kinds of allocation patterns without generally incurring high memory
455 waste through fragmentation.
457 Very large blocks (much larger than a page) are allocated with
458 @code{mmap} (anonymous or via @code{/dev/zero}) by this implementation.
459 This has the great advantage that these chunks are returned to the
460 system immediately when they are freed.  Therefore, it cannot happen
461 that a large chunk becomes ``locked'' in between smaller ones and even
462 after calling @code{free} wastes memory.  The size threshold for
463 @code{mmap} to be used can be adjusted with @code{mallopt}.  The use of
464 @code{mmap} can also be disabled completely.
466 @node Aligned Memory Blocks
467 @subsection Allocating Aligned Memory Blocks
469 @cindex page boundary
470 @cindex alignment (with @code{malloc})
471 @pindex stdlib.h
472 The address of a block returned by @code{malloc} or @code{realloc} in
473 the GNU system is always a multiple of eight (or sixteen on 64-bit
474 systems).  If you need a block whose address is a multiple of a higher
475 power of two than that, use @code{memalign} or @code{valloc}.  These
476 functions are declared in @file{stdlib.h}.
478 With the GNU library, you can use @code{free} to free the blocks that
479 @code{memalign} and @code{valloc} return.  That does not work in BSD,
480 however---BSD does not provide any way to free such blocks.
482 @comment malloc.h stdlib.h
483 @comment BSD
484 @deftypefun {void *} memalign (size_t @var{boundary}, size_t @var{size})
485 The @code{memalign} function allocates a block of @var{size} bytes whose
486 address is a multiple of @var{boundary}.  The @var{boundary} must be a
487 power of two!  The function @code{memalign} works by allocating a
488 somewhat larger block, and then returning an address within the block
489 that is on the specified boundary.
490 @end deftypefun
492 @comment malloc.h stdlib.h
493 @comment BSD
494 @deftypefun {void *} valloc (size_t @var{size})
495 Using @code{valloc} is like using @code{memalign} and passing the page size
496 as the value of the second argument.  It is implemented like this:
498 @smallexample
499 void *
500 valloc (size_t size)
502   return memalign (getpagesize (), size);
504 @end smallexample
505 @c !!! xref getpagesize
506 @end deftypefun
508 @node Malloc Tunable Parameters
509 @subsection Malloc Tunable Parameters
511 You can adjust some parameters for dynamic memory allocation with the
512 @code{mallopt} function.  This function is the general SVID/XPG
513 interface, defined in @file{malloc.h}.
514 @pindex malloc.h
516 @deftypefun int mallopt (int @var{param}, int @var{value})
517 When calling @code{mallopt}, the @var{param} argument specifies the
518 parameter to be set, and @var{value} the new value to be set.  Possible
519 choices for @var{param}, as defined in @file{malloc.h}, are:
521 @table @code
522 @item M_TRIM_THRESHOLD
523 This is the minimum size (in bytes) of the top-most, releaseable chunk
524 that will cause @code{sbrk} to be called with a negative argument in
525 order to return memory to the system.
526 @item M_TOP_PAD
527 This parameter determines the amount of extra memory to obtain from the
528 system when a call to @code{sbrk} is required.  It also specifies the
529 number of bytes to retain when shrinking the heap by calling @code{sbrk}
530 with a negative argument.  This provides the necessary hysteresis in
531 heap size such that excessive amounts of system calls can be avoided.
532 @item M_MMAP_THRESHOLD
533 All chunks larger than this value are allocated outside the normal
534 heap, using the @code{mmap} system call.  This way it is guaranteed
535 that the memory for these chunks can be returned to the system on
536 @code{free}.
537 @item M_MMAP_MAX
538 The maximum number of chunks to allocate with @code{mmap}.  Setting this
539 to zero disables all use of @code{mmap}.
540 @end table
542 @end deftypefun
544 @node Heap Consistency Checking
545 @subsection Heap Consistency Checking
547 @cindex heap consistency checking
548 @cindex consistency checking, of heap
550 You can ask @code{malloc} to check the consistency of dynamic storage by
551 using the @code{mcheck} function.  This function is a GNU extension,
552 declared in @file{mcheck.h}.
553 @pindex mcheck.h
555 @comment mcheck.h
556 @comment GNU
557 @deftypefun int mcheck (void (*@var{abortfn}) (enum mcheck_status @var{status}))
558 Calling @code{mcheck} tells @code{malloc} to perform occasional
559 consistency checks.  These will catch things such as writing
560 past the end of a block that was allocated with @code{malloc}.
562 The @var{abortfn} argument is the function to call when an inconsistency
563 is found.  If you supply a null pointer, then @code{mcheck} uses a
564 default function which prints a message and calls @code{abort}
565 (@pxref{Aborting a Program}).  The function you supply is called with
566 one argument, which says what sort of inconsistency was detected; its
567 type is described below.
569 It is too late to begin allocation checking once you have allocated
570 anything with @code{malloc}.  So @code{mcheck} does nothing in that
571 case.  The function returns @code{-1} if you call it too late, and
572 @code{0} otherwise (when it is successful).
574 The easiest way to arrange to call @code{mcheck} early enough is to use
575 the option @samp{-lmcheck} when you link your program; then you don't
576 need to modify your program source at all.  Alternately you might use
577 a debugger to insert a call to @code{mcheck} whenever the program is
578 started, for example these gdb commands will automatically call @code{mcheck}
579 whenever the program starts:
581 @smallexample
582 (gdb) break main
583 Breakpoint 1, main (argc=2, argv=0xbffff964) at whatever.c:10
584 (gdb) command 1
585 Type commands for when breakpoint 1 is hit, one per line.
586 End with a line saying just "end".
587 >call mcheck(0)
588 >continue
589 >end
590 (gdb) ...
591 @end smallexample
593 This will however only work if no initialization function of any object
594 involved calls any of the @code{malloc} functions since @code{mcheck}
595 must be called before the first such function.
597 @end deftypefun
599 @deftypefun {enum mcheck_status} mprobe (void *@var{pointer})
600 The @code{mprobe} function lets you explicitly check for inconsistencies
601 in a particular allocated block.  You must have already called
602 @code{mcheck} at the beginning of the program, to do its occasional
603 checks; calling @code{mprobe} requests an additional consistency check
604 to be done at the time of the call.
606 The argument @var{pointer} must be a pointer returned by @code{malloc}
607 or @code{realloc}.  @code{mprobe} returns a value that says what
608 inconsistency, if any, was found.  The values are described below.
609 @end deftypefun
611 @deftp {Data Type} {enum mcheck_status}
612 This enumerated type describes what kind of inconsistency was detected
613 in an allocated block, if any.  Here are the possible values:
615 @table @code
616 @item MCHECK_DISABLED
617 @code{mcheck} was not called before the first allocation.
618 No consistency checking can be done.
619 @item MCHECK_OK
620 No inconsistency detected.
621 @item MCHECK_HEAD
622 The data immediately before the block was modified.
623 This commonly happens when an array index or pointer
624 is decremented too far.
625 @item MCHECK_TAIL
626 The data immediately after the block was modified.
627 This commonly happens when an array index or pointer
628 is incremented too far.
629 @item MCHECK_FREE
630 The block was already freed.
631 @end table
632 @end deftp
634 Another possibility to check for and guard against bugs in the use of
635 @code{malloc}, @code{realloc} and @code{free} is to set the environment
636 variable @code{MALLOC_CHECK_}.  When @code{MALLOC_CHECK_} is set, a
637 special (less efficient) implementation is used which is designed to be
638 tolerant against simple errors, such as double calls of @code{free} with
639 the same argument, or overruns of a single byte (off-by-one bugs).  Not
640 all such errors can be proteced against, however, and memory leaks can
641 result.  If @code{MALLOC_CHECK_} is set to @code{0}, any detected heap
642 corruption is silently ignored; if set to @code{1}, a diagnostic is
643 printed on @code{stderr}; if set to @code{2}, @code{abort} is called
644 immediately.  This can be useful because otherwise a crash may happen
645 much later, and the true cause for the problem is then very hard to
646 track down.
648 So, what's the difference between using @code{MALLOC_CHECK_} and linking
649 with @samp{-lmcheck}?  @code{MALLOC_CHECK_} is orthognal with respect to
650 @samp{-lmcheck}.  @samp{-lmcheck} has been added for backward
651 compatibility.  Both @code{MALLOC_CHECK_} and @samp{-lmcheck} should
652 uncover the same bugs - but using @code{MALLOC_CHECK_} you don't need to
653 recompile your application.
655 @node Hooks for Malloc
656 @subsection Storage Allocation Hooks
657 @cindex allocation hooks, for @code{malloc}
659 The GNU C library lets you modify the behavior of @code{malloc},
660 @code{realloc}, and @code{free} by specifying appropriate hook
661 functions.  You can use these hooks to help you debug programs that use
662 dynamic storage allocation, for example.
664 The hook variables are declared in @file{malloc.h}.
665 @pindex malloc.h
667 @comment malloc.h
668 @comment GNU
669 @defvar __malloc_hook
670 The value of this variable is a pointer to function that @code{malloc}
671 uses whenever it is called.  You should define this function to look
672 like @code{malloc}; that is, like:
674 @smallexample
675 void *@var{function} (size_t @var{size}, void *@var{caller})
676 @end smallexample
678 The value of @var{caller} is the return address found on the stack when
679 the @code{malloc} function was called.  This value allows to trace the
680 memory consumption of the program.
681 @end defvar
683 @comment malloc.h
684 @comment GNU
685 @defvar __realloc_hook
686 The value of this variable is a pointer to function that @code{realloc}
687 uses whenever it is called.  You should define this function to look
688 like @code{realloc}; that is, like:
690 @smallexample
691 void *@var{function} (void *@var{ptr}, size_t @var{size}, void *@var{caller})
692 @end smallexample
694 The value of @var{caller} is the return address found on the stack when
695 the @code{realloc} function was called.  This value allows to trace the
696 memory consumption of the program.
697 @end defvar
699 @comment malloc.h
700 @comment GNU
701 @defvar __free_hook
702 The value of this variable is a pointer to function that @code{free}
703 uses whenever it is called.  You should define this function to look
704 like @code{free}; that is, like:
706 @smallexample
707 void @var{function} (void *@var{ptr}, void *@var{caller})
708 @end smallexample
710 The value of @var{caller} is the return address found on the stack when
711 the @code{free} function was called.  This value allows to trace the
712 memory consumption of the program.
713 @end defvar
715 @comment malloc.h
716 @comment GNU
717 @defvar __memalign_hook
718 The value of this variable is a pointer to function that @code{memalign}
719 uses whenever it is called.  You should define this function to look
720 like @code{memalign}; that is, like:
722 @smallexample
723 void *@var{function} (size_t @var{size}, size_t @var{alignment})
724 @end smallexample
725 @end defvar
727 You must make sure that the function you install as a hook for one of
728 these functions does not call that function recursively without restoring
729 the old value of the hook first!  Otherwise, your program will get stuck
730 in an infinite recursion.  Before calling the function recursively, one
731 should make sure to restore all the hooks to their previous value.  When
732 coming back from the recursive call, all the hooks should be resaved
733 since a hook might modify itself.
735 Here is an example showing how to use @code{__malloc_hook} and
736 @code{__free_hook} properly.  It installs a function that prints out
737 information every time @code{malloc} or @code{free} is called.  We just
738 assume here that @code{realloc} and @code{memalign} are not used in our
739 program.
741 @smallexample
742 /* Global variables used to hold underlaying hook values.  */
743 static void *(*old_malloc_hook) (size_t);
744 static void (*old_free_hook) (void*);
746 /* Prototypes for our hooks.  */
747 static void *my_malloc_hook (size_t);
748 static void my_free_hook(void*);
750 static void *
751 my_malloc_hook (size_t size)
753   void *result;
754   /* Restore all old hooks */
755   __malloc_hook = old_malloc_hook;
756   __free_hook = old_free_hook;
757   /* Call recursively */
758   result = malloc (size);
759   /* Save underlaying hooks */
760   old_malloc_hook = __malloc_hook;
761   old_free_hook = __free_hook;
762   /* @r{@code{printf} might call @code{malloc}, so protect it too.} */
763   printf ("malloc (%u) returns %p\n", (unsigned int) size, result);
764   /* Restore our own hooks */
765   __malloc_hook = my_malloc_hook;
766   __free_hook = my_free_hook;
767   return result;
770 static void *
771 my_free_hook (void *ptr)
773   /* Restore all old hooks */
774   __malloc_hook = old_malloc_hook;
775   __free_hook = old_free_hook;
776   /* Call recursively */
777   free (ptr);
778   /* Save underlaying hooks */
779   old_malloc_hook = __malloc_hook;
780   old_free_hook = __free_hook;
781   /* @r{@code{printf} might call @code{free}, so protect it too.} */
782   printf ("freed pointer %p\n", ptr);
783   /* Restore our own hooks */
784   __malloc_hook = my_malloc_hook;
785   __free_hook = my_free_hook;
788 main ()
790   ...
791   old_malloc_hook = __malloc_hook;
792   old_free_hook = __free_hook;
793   __malloc_hook = my_malloc_hook;
794   __free_hook = my_free_hook;
795   ...
797 @end smallexample
799 The @code{mcheck} function (@pxref{Heap Consistency Checking}) works by
800 installing such hooks.
802 @c __morecore, __after_morecore_hook are undocumented
803 @c It's not clear whether to document them.
805 @node Statistics of Malloc
806 @subsection Statistics for Storage Allocation with @code{malloc}
808 @cindex allocation statistics
809 You can get information about dynamic storage allocation by calling the
810 @code{mallinfo} function.  This function and its associated data type
811 are declared in @file{malloc.h}; they are an extension of the standard
812 SVID/XPG version.
813 @pindex malloc.h
815 @comment malloc.h
816 @comment GNU
817 @deftp {Data Type} {struct mallinfo}
818 This structure type is used to return information about the dynamic
819 storage allocator.  It contains the following members:
821 @table @code
822 @item int arena
823 This is the total size of memory allocated with @code{sbrk} by
824 @code{malloc}, in bytes.
826 @item int ordblks
827 This is the number of chunks not in use.  (The storage allocator
828 internally gets chunks of memory from the operating system, and then
829 carves them up to satisfy individual @code{malloc} requests; see
830 @ref{Efficiency and Malloc}.)
832 @item int smblks
833 This field is unused.
835 @item int hblks
836 This is the total number of chunks allocated with @code{mmap}.
838 @item int hblkhd
839 This is the total size of memory allocated with @code{mmap}, in bytes.
841 @item int usmblks
842 This field is unused.
844 @item int fsmblks
845 This field is unused.
847 @item int uordblks
848 This is the total size of memory occupied by chunks handed out by
849 @code{malloc}.
851 @item int fordblks
852 This is the total size of memory occupied by free (not in use) chunks.
854 @item int keepcost
855 This is the size of the top-most, releaseable chunk that normally
856 borders the end of the heap (i.e. the ``brk'' of the process).
858 @end table
859 @end deftp
861 @comment malloc.h
862 @comment SVID
863 @deftypefun {struct mallinfo} mallinfo (void)
864 This function returns information about the current dynamic memory usage
865 in a structure of type @code{struct mallinfo}.
866 @end deftypefun
868 @node Summary of Malloc
869 @subsection Summary of @code{malloc}-Related Functions
871 Here is a summary of the functions that work with @code{malloc}:
873 @table @code
874 @item void *malloc (size_t @var{size})
875 Allocate a block of @var{size} bytes.  @xref{Basic Allocation}.
877 @item void free (void *@var{addr})
878 Free a block previously allocated by @code{malloc}.  @xref{Freeing after
879 Malloc}.
881 @item void *realloc (void *@var{addr}, size_t @var{size})
882 Make a block previously allocated by @code{malloc} larger or smaller,
883 possibly by copying it to a new location.  @xref{Changing Block Size}.
885 @item void *calloc (size_t @var{count}, size_t @var{eltsize})
886 Allocate a block of @var{count} * @var{eltsize} bytes using
887 @code{malloc}, and set its contents to zero.  @xref{Allocating Cleared
888 Space}.
890 @item void *valloc (size_t @var{size})
891 Allocate a block of @var{size} bytes, starting on a page boundary.
892 @xref{Aligned Memory Blocks}.
894 @item void *memalign (size_t @var{size}, size_t @var{boundary})
895 Allocate a block of @var{size} bytes, starting on an address that is a
896 multiple of @var{boundary}.  @xref{Aligned Memory Blocks}.
898 @item int mallopt (int @var{param}, int @var{value})
899 Adjust a tunable parameter.  @xref{Malloc Tunable Parameters}.
901 @item int mcheck (void (*@var{abortfn}) (void))
902 Tell @code{malloc} to perform occasional consistency checks on
903 dynamically allocated memory, and to call @var{abortfn} when an
904 inconsistency is found.  @xref{Heap Consistency Checking}.
906 @item void *(*__malloc_hook) (size_t @var{size}, void *@var{caller})
907 A pointer to a function that @code{malloc} uses whenever it is called.
909 @item void *(*__realloc_hook) (void *@var{ptr}, size_t @var{size}, void *@var{caller})
910 A pointer to a function that @code{realloc} uses whenever it is called.
912 @item void (*__free_hook) (void *@var{ptr}, void *@var{caller})
913 A pointer to a function that @code{free} uses whenever it is called.
915 @item void (*__memalign_hook) (size_t @var{size}, size_t @var{alignment})
916 A pointer to a function that @code{memalign} uses whenever it is called.
918 @item struct mallinfo mallinfo (void)
919 Return information about the current dynamic memory usage.
920 @xref{Statistics of Malloc}.
921 @end table
923 @node Allocation Debugging
924 @section Allocation Debugging
925 @cindex allocation debugging
926 @cindex malloc debugger
928 An complicated task when programming with languages which do not use
929 garbage collected dynamic memory allocation is to find memory leaks.
930 Long running programs must assure that dynamically allocated objects are
931 freed at the end of their lifetime.  If this does not happen the system
932 runs out of memory, sooner or later.
934 The @code{malloc} implementation in the GNU C library provides some
935 simple means to detect sich leaks and provide some information to find
936 the location.  To do this the application must be started in a special
937 mode which is enabled by an environment variable.  There are no speed
938 penalties if the program is compiled in preparation of the debugging if
939 the debug mode is not enabled.
941 @menu
942 * Tracing malloc::               How to install the tracing functionality.
943 * Using the Memory Debugger::    Example programs excerpts.
944 * Tips for the Memory Debugger:: Some more or less clever ideas.
945 * Interpreting the traces::      What do all these lines mean?
946 @end menu
948 @node Tracing malloc
949 @subsection How to install the tracing functionality
951 @comment mcheck.h
952 @comment GNU
953 @deftypefun void mtrace (void)
954 When the @code{mtrace} function is called it looks for an environment
955 variable named @code{MALLOC_TRACE}.  This variable is supposed to
956 contain a valid file name.  The user must have write access.  If the
957 file already exists it is truncated.  If the environment variable is not
958 set or it does not name a valid file which can be opened for writing
959 nothing is done.  The behaviour of @code{malloc} etc. is not changed.
960 For obvious reasons this also happens if the application is install SUID
961 or SGID.
963 If the named file is successfully opened @code{mtrace} installs special
964 handlers for the functions @code{malloc}, @code{realloc}, and
965 @code{free} (@pxref{Hooks for Malloc}).  From now on all uses of these
966 functions are traced and protocolled into the file.  There is now of
967 course a speed penalty for all calls to the traced functions so that the
968 tracing should not be enabled during their normal use.
970 This function is a GNU extension and generally not available on other
971 systems.  The prototype can be found in @file{mcheck.h}.
972 @end deftypefun
974 @comment mcheck.h
975 @comment GNU
976 @deftypefun void muntrace (void)
977 The @code{muntrace} function can be called after @code{mtrace} was used
978 to enable tracing the @code{malloc} calls.  If no (succesful) call of
979 @code{mtrace} was made @code{muntrace} does nothing.
981 Otherwise it deinstalls the handlers for @code{malloc}, @code{realloc},
982 and @code{free} and then closes the protocol file.  No calls are
983 protocolled anymore and the programs runs again with the full speed.
985 This function is a GNU extension and generally not available on other
986 systems.  The prototype can be found in @file{mcheck.h}.
987 @end deftypefun
989 @node Using the Memory Debugger
990 @subsection Example programs excerpts
992 Even though the tracing functionality does not influence the runtime
993 behaviour of the program it is no wise idea to call @code{mtrace} in all
994 programs.  Just imagine you debug a program using @code{mtrace} and all
995 other programs used in the debug sessions also trace their @code{malloc}
996 calls.  The output file would be the same for all programs and so is
997 unusable.  Therefore one should call @code{mtrace} only if compiled for
998 debugging.  A program could therefore start like this:
1000 @example
1001 #include <mcheck.h>
1004 main (int argc, char *argv[])
1006 #ifdef DEBUGGING
1007   mtrace ();
1008 #endif
1009   @dots{}
1011 @end example
1013 This is all what is needed if you want to trace the calls during the
1014 whole runtime of the program.  Alternatively you can stop the tracing at
1015 any time with a call to @code{muntrace}.  It is even possible to restart
1016 the tracing again with a new call to @code{mtrace}.  But this can course
1017 unreliable results since there are possibly calls of the functions which
1018 are not called.  Please note that not only the application uses the
1019 traced functions, also libraries (including the C library itself) use
1020 this function.
1022 This last point is also why it is no good idea to call @code{muntrace}
1023 before the program terminated.  The libraries are informed about the
1024 termination of the program only after the program returns from
1025 @code{main} or calls @code{exit} and so cannot free the memory they use
1026 before this time.
1028 So the best thing one can do is to call @code{mtrace} as the very first
1029 function in the program and never call @code{muntrace}.  So the program
1030 traces almost all uses of the @code{malloc} functions (except those
1031 calls which are executed by constructors of the program or used
1032 libraries).
1034 @node Tips for the Memory Debugger
1035 @subsection Some more or less clever ideas
1037 You know the situation.  The program is prepared for debugging and in
1038 all debugging sessions it runs well.  But once it is started without
1039 debugging the error shows up.  In our situation here: the memory leaks
1040 becomes visible only when we just turned off the debugging.  If you
1041 foresee such situations you can still win.  Simply use something
1042 equivalent to the following little program:
1044 @example
1045 #include <mcheck.h>
1046 #include <signal.h>
1048 static void
1049 enable (int sig)
1051   mtrace ();
1052   signal (SIGUSR1, enable);
1055 static void
1056 disable (int sig)
1058   muntrace ();
1059   signal (SIGUSR2, disable);
1063 main (int argc, char *argv[])
1065   @dots{}
1067   signal (SIGUSR1, enable);
1068   signal (SIGUSR2, disable);
1070   @dots{}
1072 @end example
1074 I.e., the user can start the memory debugger any time s/he wants if the
1075 program was started with @code{MALLOC_TRACE} set in the environment.
1076 The output will of course not show the allocations which happened before
1077 the first signal but if there is a memory leak this will show up
1078 nevertheless.
1080 @node Interpreting the traces
1081 @subsection Interpreting the traces
1083 If you take a look at the output it will look similar to this:
1085 @example
1086 = Start
1087 @ [0x8048209] - 0x8064cc8
1088 @ [0x8048209] - 0x8064ce0
1089 @ [0x8048209] - 0x8064cf8
1090 @ [0x80481eb] + 0x8064c48 0x14
1091 @ [0x80481eb] + 0x8064c60 0x14
1092 @ [0x80481eb] + 0x8064c78 0x14
1093 @ [0x80481eb] + 0x8064c90 0x14
1094 = End
1095 @end example
1097 What this all means is not really important since the trace file is not
1098 meant to be read by a human.  Therefore no attention is payed to good
1099 readability.  Instead there is a program which comes with the GNU C
1100 library which interprets the traces and outputs a summary in on
1101 user-friendly way.  The program is called @code{mtrace} (it is in fact a
1102 Perl script) and it takes one or two arguments.  In any case the name of
1103 the file with the trace output must be specified.  If an optional argument
1104 precedes the name of the trace file this must be the name of the program
1105 which generated the trace.
1107 @example
1108 drepper$ mtrace tst-mtrace log
1109 No memory leaks.
1110 @end example
1112 In this case the program @code{tst-mtrace} was run and it produced a
1113 trace file @file{log}.  The message printed by @code{mtrace} shows there
1114 are no problems with the code, all allocated memory was freed
1115 afterwards.
1117 If we call @code{mtrace} on the example trace given above we would get a
1118 different outout:
1120 @example
1121 drepper$ mtrace errlog
1122 - 0x08064cc8 Free 2 was never alloc'd 0x8048209
1123 - 0x08064ce0 Free 3 was never alloc'd 0x8048209
1124 - 0x08064cf8 Free 4 was never alloc'd 0x8048209
1126 Memory not freed:
1127 -----------------
1128    Address     Size     Caller
1129 0x08064c48     0x14  at 0x80481eb
1130 0x08064c60     0x14  at 0x80481eb
1131 0x08064c78     0x14  at 0x80481eb
1132 0x08064c90     0x14  at 0x80481eb
1133 @end example
1135 We have called @code{mtrace} with only one argument and so the script
1136 has no chance to find out what is meant with the addresses given in the
1137 trace.  We can do better:
1139 @example
1140 drepper$ mtrace tst-mtrace errlog
1141 - 0x08064cc8 Free 2 was never alloc'd /home/drepper/tst-mtrace.c:39
1142 - 0x08064ce0 Free 3 was never alloc'd /home/drepper/tst-mtrace.c:39
1143 - 0x08064cf8 Free 4 was never alloc'd /home/drepper/tst-mtrace.c:39
1145 Memory not freed:
1146 -----------------
1147    Address     Size     Caller
1148 0x08064c48     0x14  at /home/drepper/tst-mtrace.c:33
1149 0x08064c60     0x14  at /home/drepper/tst-mtrace.c:33
1150 0x08064c78     0x14  at /home/drepper/tst-mtrace.c:33
1151 0x08064c90     0x14  at /home/drepper/tst-mtrace.c:33
1152 @end example
1154 Suddenly the output makes much more sense and the user can see
1155 immediately where the function calls causing the trouble can be found.
1157 Interpreting this output is not complicated.  There are at most two
1158 different situations being detected.  First, @code{free} was called for
1159 pointers which were never returned by one of the allocation functions.
1160 This is usually a very bad problem and how this looks like is shown in
1161 the first three lines of the output.  Situations like this are quite
1162 rare and if they appear they show up very drastically: the program
1163 normally crashes.
1165 The other situation which is much harder to detect are memory leaks.  As
1166 you can see in the output the @code{mtrace} function collects all this
1167 information and so can say that the program calls an allocation function
1168 from line 33 in the source file @file{/home/drepper/tst-mtrace.c} four
1169 times without freeing this memory before the program terminates.
1170 Whether this is a real problem keeps to be investigated.
1172 @node Obstacks
1173 @section Obstacks
1174 @cindex obstacks
1176 An @dfn{obstack} is a pool of memory containing a stack of objects.  You
1177 can create any number of separate obstacks, and then allocate objects in
1178 specified obstacks.  Within each obstack, the last object allocated must
1179 always be the first one freed, but distinct obstacks are independent of
1180 each other.
1182 Aside from this one constraint of order of freeing, obstacks are totally
1183 general: an obstack can contain any number of objects of any size.  They
1184 are implemented with macros, so allocation is usually very fast as long as
1185 the objects are usually small.  And the only space overhead per object is
1186 the padding needed to start each object on a suitable boundary.
1188 @menu
1189 * Creating Obstacks::           How to declare an obstack in your program.
1190 * Preparing for Obstacks::      Preparations needed before you can
1191                                  use obstacks.
1192 * Allocation in an Obstack::    Allocating objects in an obstack.
1193 * Freeing Obstack Objects::     Freeing objects in an obstack.
1194 * Obstack Functions::           The obstack functions are both
1195                                  functions and macros.
1196 * Growing Objects::             Making an object bigger by stages.
1197 * Extra Fast Growing::          Extra-high-efficiency (though more
1198                                  complicated) growing objects.
1199 * Status of an Obstack::        Inquiries about the status of an obstack.
1200 * Obstacks Data Alignment::     Controlling alignment of objects in obstacks.
1201 * Obstack Chunks::              How obstacks obtain and release chunks;
1202                                  efficiency considerations.
1203 * Summary of Obstacks::
1204 @end menu
1206 @node Creating Obstacks
1207 @subsection Creating Obstacks
1209 The utilities for manipulating obstacks are declared in the header
1210 file @file{obstack.h}.
1211 @pindex obstack.h
1213 @comment obstack.h
1214 @comment GNU
1215 @deftp {Data Type} {struct obstack}
1216 An obstack is represented by a data structure of type @code{struct
1217 obstack}.  This structure has a small fixed size; it records the status
1218 of the obstack and how to find the space in which objects are allocated.
1219 It does not contain any of the objects themselves.  You should not try
1220 to access the contents of the structure directly; use only the functions
1221 described in this chapter.
1222 @end deftp
1224 You can declare variables of type @code{struct obstack} and use them as
1225 obstacks, or you can allocate obstacks dynamically like any other kind
1226 of object.  Dynamic allocation of obstacks allows your program to have a
1227 variable number of different stacks.  (You can even allocate an
1228 obstack structure in another obstack, but this is rarely useful.)
1230 All the functions that work with obstacks require you to specify which
1231 obstack to use.  You do this with a pointer of type @code{struct obstack
1232 *}.  In the following, we often say ``an obstack'' when strictly
1233 speaking the object at hand is such a pointer.
1235 The objects in the obstack are packed into large blocks called
1236 @dfn{chunks}.  The @code{struct obstack} structure points to a chain of
1237 the chunks currently in use.
1239 The obstack library obtains a new chunk whenever you allocate an object
1240 that won't fit in the previous chunk.  Since the obstack library manages
1241 chunks automatically, you don't need to pay much attention to them, but
1242 you do need to supply a function which the obstack library should use to
1243 get a chunk.  Usually you supply a function which uses @code{malloc}
1244 directly or indirectly.  You must also supply a function to free a chunk.
1245 These matters are described in the following section.
1247 @node Preparing for Obstacks
1248 @subsection Preparing for Using Obstacks
1250 Each source file in which you plan to use the obstack functions
1251 must include the header file @file{obstack.h}, like this:
1253 @smallexample
1254 #include <obstack.h>
1255 @end smallexample
1257 @findex obstack_chunk_alloc
1258 @findex obstack_chunk_free
1259 Also, if the source file uses the macro @code{obstack_init}, it must
1260 declare or define two functions or macros that will be called by the
1261 obstack library.  One, @code{obstack_chunk_alloc}, is used to allocate
1262 the chunks of memory into which objects are packed.  The other,
1263 @code{obstack_chunk_free}, is used to return chunks when the objects in
1264 them are freed.  These macros should appear before any use of obstacks
1265 in the source file.
1267 Usually these are defined to use @code{malloc} via the intermediary
1268 @code{xmalloc} (@pxref{Unconstrained Allocation}).  This is done with
1269 the following pair of macro definitions:
1271 @smallexample
1272 #define obstack_chunk_alloc xmalloc
1273 #define obstack_chunk_free free
1274 @end smallexample
1276 @noindent
1277 Though the storage you get using obstacks really comes from @code{malloc},
1278 using obstacks is faster because @code{malloc} is called less often, for
1279 larger blocks of memory.  @xref{Obstack Chunks}, for full details.
1281 At run time, before the program can use a @code{struct obstack} object
1282 as an obstack, it must initialize the obstack by calling
1283 @code{obstack_init}.
1285 @comment obstack.h
1286 @comment GNU
1287 @deftypefun int obstack_init (struct obstack *@var{obstack-ptr})
1288 Initialize obstack @var{obstack-ptr} for allocation of objects.  This
1289 function calls the obstack's @code{obstack_chunk_alloc} function.  If
1290 allocation of memory fails, the function pointed to by
1291 @code{obstack_alloc_failed_handler} is called.  The @code{obstack_init}
1292 function always returns 1 (Compatibility notice: Former versions of
1293 obstack returned 0 if allocation failed).
1294 @end deftypefun
1296 Here are two examples of how to allocate the space for an obstack and
1297 initialize it.  First, an obstack that is a static variable:
1299 @smallexample
1300 static struct obstack myobstack;
1301 @dots{}
1302 obstack_init (&myobstack);
1303 @end smallexample
1305 @noindent
1306 Second, an obstack that is itself dynamically allocated:
1308 @smallexample
1309 struct obstack *myobstack_ptr
1310   = (struct obstack *) xmalloc (sizeof (struct obstack));
1312 obstack_init (myobstack_ptr);
1313 @end smallexample
1315 @comment obstack.h
1316 @comment GNU
1317 @defvar obstack_alloc_failed_handler
1318 The value of this variable is a pointer to a function that
1319 @code{obstack} uses when @code{obstack_chunk_alloc} fails to allocate
1320 memory.  The default action is to print a message and abort.
1321 You should supply a function that either calls @code{exit}
1322 (@pxref{Program Termination}) or @code{longjmp} (@pxref{Non-Local
1323 Exits}) and doesn't return.
1325 @smallexample
1326 void my_obstack_alloc_failed (void)
1327 @dots{}
1328 obstack_alloc_failed_handler = &my_obstack_alloc_failed;
1329 @end smallexample
1331 @end defvar
1333 @node Allocation in an Obstack
1334 @subsection Allocation in an Obstack
1335 @cindex allocation (obstacks)
1337 The most direct way to allocate an object in an obstack is with
1338 @code{obstack_alloc}, which is invoked almost like @code{malloc}.
1340 @comment obstack.h
1341 @comment GNU
1342 @deftypefun {void *} obstack_alloc (struct obstack *@var{obstack-ptr}, int @var{size})
1343 This allocates an uninitialized block of @var{size} bytes in an obstack
1344 and returns its address.  Here @var{obstack-ptr} specifies which obstack
1345 to allocate the block in; it is the address of the @code{struct obstack}
1346 object which represents the obstack.  Each obstack function or macro
1347 requires you to specify an @var{obstack-ptr} as the first argument.
1349 This function calls the obstack's @code{obstack_chunk_alloc} function if
1350 it needs to allocate a new chunk of memory; it calls
1351 @code{obstack_alloc_failed_handler} if allocation of memory by
1352 @code{obstack_chunk_alloc} failed.
1353 @end deftypefun
1355 For example, here is a function that allocates a copy of a string @var{str}
1356 in a specific obstack, which is in the variable @code{string_obstack}:
1358 @smallexample
1359 struct obstack string_obstack;
1361 char *
1362 copystring (char *string)
1364   size_t len = strlen (string) + 1;
1365   char *s = (char *) obstack_alloc (&string_obstack, len);
1366   memcpy (s, string, len);
1367   return s;
1369 @end smallexample
1371 To allocate a block with specified contents, use the function
1372 @code{obstack_copy}, declared like this:
1374 @comment obstack.h
1375 @comment GNU
1376 @deftypefun {void *} obstack_copy (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1377 This allocates a block and initializes it by copying @var{size}
1378 bytes of data starting at @var{address}.  It calls
1379 @code{obstack_alloc_failed_handler} if allocation of memory by
1380 @code{obstack_chunk_alloc} failed.
1381 @end deftypefun
1383 @comment obstack.h
1384 @comment GNU
1385 @deftypefun {void *} obstack_copy0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1386 Like @code{obstack_copy}, but appends an extra byte containing a null
1387 character.  This extra byte is not counted in the argument @var{size}.
1388 @end deftypefun
1390 The @code{obstack_copy0} function is convenient for copying a sequence
1391 of characters into an obstack as a null-terminated string.  Here is an
1392 example of its use:
1394 @smallexample
1395 char *
1396 obstack_savestring (char *addr, int size)
1398   return obstack_copy0 (&myobstack, addr, size);
1400 @end smallexample
1402 @noindent
1403 Contrast this with the previous example of @code{savestring} using
1404 @code{malloc} (@pxref{Basic Allocation}).
1406 @node Freeing Obstack Objects
1407 @subsection Freeing Objects in an Obstack
1408 @cindex freeing (obstacks)
1410 To free an object allocated in an obstack, use the function
1411 @code{obstack_free}.  Since the obstack is a stack of objects, freeing
1412 one object automatically frees all other objects allocated more recently
1413 in the same obstack.
1415 @comment obstack.h
1416 @comment GNU
1417 @deftypefun void obstack_free (struct obstack *@var{obstack-ptr}, void *@var{object})
1418 If @var{object} is a null pointer, everything allocated in the obstack
1419 is freed.  Otherwise, @var{object} must be the address of an object
1420 allocated in the obstack.  Then @var{object} is freed, along with
1421 everything allocated in @var{obstack} since @var{object}.
1422 @end deftypefun
1424 Note that if @var{object} is a null pointer, the result is an
1425 uninitialized obstack.  To free all storage in an obstack but leave it
1426 valid for further allocation, call @code{obstack_free} with the address
1427 of the first object allocated on the obstack:
1429 @smallexample
1430 obstack_free (obstack_ptr, first_object_allocated_ptr);
1431 @end smallexample
1433 Recall that the objects in an obstack are grouped into chunks.  When all
1434 the objects in a chunk become free, the obstack library automatically
1435 frees the chunk (@pxref{Preparing for Obstacks}).  Then other
1436 obstacks, or non-obstack allocation, can reuse the space of the chunk.
1438 @node Obstack Functions
1439 @subsection Obstack Functions and Macros
1440 @cindex macros
1442 The interfaces for using obstacks may be defined either as functions or
1443 as macros, depending on the compiler.  The obstack facility works with
1444 all C compilers, including both @w{ISO C} and traditional C, but there are
1445 precautions you must take if you plan to use compilers other than GNU C.
1447 If you are using an old-fashioned @w{non-ISO C} compiler, all the obstack
1448 ``functions'' are actually defined only as macros.  You can call these
1449 macros like functions, but you cannot use them in any other way (for
1450 example, you cannot take their address).
1452 Calling the macros requires a special precaution: namely, the first
1453 operand (the obstack pointer) may not contain any side effects, because
1454 it may be computed more than once.  For example, if you write this:
1456 @smallexample
1457 obstack_alloc (get_obstack (), 4);
1458 @end smallexample
1460 @noindent
1461 you will find that @code{get_obstack} may be called several times.
1462 If you use @code{*obstack_list_ptr++} as the obstack pointer argument,
1463 you will get very strange results since the incrementation may occur
1464 several times.
1466 In @w{ISO C}, each function has both a macro definition and a function
1467 definition.  The function definition is used if you take the address of the
1468 function without calling it.  An ordinary call uses the macro definition by
1469 default, but you can request the function definition instead by writing the
1470 function name in parentheses, as shown here:
1472 @smallexample
1473 char *x;
1474 void *(*funcp) ();
1475 /* @r{Use the macro}.  */
1476 x = (char *) obstack_alloc (obptr, size);
1477 /* @r{Call the function}.  */
1478 x = (char *) (obstack_alloc) (obptr, size);
1479 /* @r{Take the address of the function}.  */
1480 funcp = obstack_alloc;
1481 @end smallexample
1483 @noindent
1484 This is the same situation that exists in @w{ISO C} for the standard library
1485 functions.  @xref{Macro Definitions}.
1487 @strong{Warning:} When you do use the macros, you must observe the
1488 precaution of avoiding side effects in the first operand, even in @w{ISO C}.
1490 If you use the GNU C compiler, this precaution is not necessary, because
1491 various language extensions in GNU C permit defining the macros so as to
1492 compute each argument only once.
1494 @node Growing Objects
1495 @subsection Growing Objects
1496 @cindex growing objects (in obstacks)
1497 @cindex changing the size of a block (obstacks)
1499 Because storage in obstack chunks is used sequentially, it is possible to
1500 build up an object step by step, adding one or more bytes at a time to the
1501 end of the object.  With this technique, you do not need to know how much
1502 data you will put in the object until you come to the end of it.  We call
1503 this the technique of @dfn{growing objects}.  The special functions
1504 for adding data to the growing object are described in this section.
1506 You don't need to do anything special when you start to grow an object.
1507 Using one of the functions to add data to the object automatically
1508 starts it.  However, it is necessary to say explicitly when the object is
1509 finished.  This is done with the function @code{obstack_finish}.
1511 The actual address of the object thus built up is not known until the
1512 object is finished.  Until then, it always remains possible that you will
1513 add so much data that the object must be copied into a new chunk.
1515 While the obstack is in use for a growing object, you cannot use it for
1516 ordinary allocation of another object.  If you try to do so, the space
1517 already added to the growing object will become part of the other object.
1519 @comment obstack.h
1520 @comment GNU
1521 @deftypefun void obstack_blank (struct obstack *@var{obstack-ptr}, int @var{size})
1522 The most basic function for adding to a growing object is
1523 @code{obstack_blank}, which adds space without initializing it.
1524 @end deftypefun
1526 @comment obstack.h
1527 @comment GNU
1528 @deftypefun void obstack_grow (struct obstack *@var{obstack-ptr}, void *@var{data}, int @var{size})
1529 To add a block of initialized space, use @code{obstack_grow}, which is
1530 the growing-object analogue of @code{obstack_copy}.  It adds @var{size}
1531 bytes of data to the growing object, copying the contents from
1532 @var{data}.
1533 @end deftypefun
1535 @comment obstack.h
1536 @comment GNU
1537 @deftypefun void obstack_grow0 (struct obstack *@var{obstack-ptr}, void *@var{data}, int @var{size})
1538 This is the growing-object analogue of @code{obstack_copy0}.  It adds
1539 @var{size} bytes copied from @var{data}, followed by an additional null
1540 character.
1541 @end deftypefun
1543 @comment obstack.h
1544 @comment GNU
1545 @deftypefun void obstack_1grow (struct obstack *@var{obstack-ptr}, char @var{c})
1546 To add one character at a time, use the function @code{obstack_1grow}.
1547 It adds a single byte containing @var{c} to the growing object.
1548 @end deftypefun
1550 @comment obstack.h
1551 @comment GNU
1552 @deftypefun void obstack_ptr_grow (struct obstack *@var{obstack-ptr}, void *@var{data})
1553 Adding the value of a pointer one can use the function
1554 @code{obstack_ptr_grow}.  It adds @code{sizeof (void *)} bytes
1555 containing the value of @var{data}.
1556 @end deftypefun
1558 @comment obstack.h
1559 @comment GNU
1560 @deftypefun void obstack_int_grow (struct obstack *@var{obstack-ptr}, int @var{data})
1561 A single value of type @code{int} can be added by using the
1562 @code{obstack_int_grow} function.  It adds @code{sizeof (int)} bytes to
1563 the growing object and initializes them with the value of @var{data}.
1564 @end deftypefun
1566 @comment obstack.h
1567 @comment GNU
1568 @deftypefun {void *} obstack_finish (struct obstack *@var{obstack-ptr})
1569 When you are finished growing the object, use the function
1570 @code{obstack_finish} to close it off and return its final address.
1572 Once you have finished the object, the obstack is available for ordinary
1573 allocation or for growing another object.
1575 This function can return a null pointer under the same conditions as
1576 @code{obstack_alloc} (@pxref{Allocation in an Obstack}).
1577 @end deftypefun
1579 When you build an object by growing it, you will probably need to know
1580 afterward how long it became.  You need not keep track of this as you grow
1581 the object, because you can find out the length from the obstack just
1582 before finishing the object with the function @code{obstack_object_size},
1583 declared as follows:
1585 @comment obstack.h
1586 @comment GNU
1587 @deftypefun int obstack_object_size (struct obstack *@var{obstack-ptr})
1588 This function returns the current size of the growing object, in bytes.
1589 Remember to call this function @emph{before} finishing the object.
1590 After it is finished, @code{obstack_object_size} will return zero.
1591 @end deftypefun
1593 If you have started growing an object and wish to cancel it, you should
1594 finish it and then free it, like this:
1596 @smallexample
1597 obstack_free (obstack_ptr, obstack_finish (obstack_ptr));
1598 @end smallexample
1600 @noindent
1601 This has no effect if no object was growing.
1603 @cindex shrinking objects
1604 You can use @code{obstack_blank} with a negative size argument to make
1605 the current object smaller.  Just don't try to shrink it beyond zero
1606 length---there's no telling what will happen if you do that.
1608 @node Extra Fast Growing
1609 @subsection Extra Fast Growing Objects
1610 @cindex efficiency and obstacks
1612 The usual functions for growing objects incur overhead for checking
1613 whether there is room for the new growth in the current chunk.  If you
1614 are frequently constructing objects in small steps of growth, this
1615 overhead can be significant.
1617 You can reduce the overhead by using special ``fast growth''
1618 functions that grow the object without checking.  In order to have a
1619 robust program, you must do the checking yourself.  If you do this checking
1620 in the simplest way each time you are about to add data to the object, you
1621 have not saved anything, because that is what the ordinary growth
1622 functions do.  But if you can arrange to check less often, or check
1623 more efficiently, then you make the program faster.
1625 The function @code{obstack_room} returns the amount of room available
1626 in the current chunk.  It is declared as follows:
1628 @comment obstack.h
1629 @comment GNU
1630 @deftypefun int obstack_room (struct obstack *@var{obstack-ptr})
1631 This returns the number of bytes that can be added safely to the current
1632 growing object (or to an object about to be started) in obstack
1633 @var{obstack} using the fast growth functions.
1634 @end deftypefun
1636 While you know there is room, you can use these fast growth functions
1637 for adding data to a growing object:
1639 @comment obstack.h
1640 @comment GNU
1641 @deftypefun void obstack_1grow_fast (struct obstack *@var{obstack-ptr}, char @var{c})
1642 The function @code{obstack_1grow_fast} adds one byte containing the
1643 character @var{c} to the growing object in obstack @var{obstack-ptr}.
1644 @end deftypefun
1646 @comment obstack.h
1647 @comment GNU
1648 @deftypefun void obstack_ptr_grow_fast (struct obstack *@var{obstack-ptr}, void *@var{data})
1649 The function @code{obstack_ptr_grow_fast} adds @code{sizeof (void *)}
1650 bytes containing the value of @var{data} to the growing object in
1651 obstack @var{obstack-ptr}.
1652 @end deftypefun
1654 @comment obstack.h
1655 @comment GNU
1656 @deftypefun void obstack_int_grow_fast (struct obstack *@var{obstack-ptr}, int @var{data})
1657 The function @code{obstack_int_grow_fast} adds @code{sizeof (int)} bytes
1658 containing the value of @var{data} to the growing object in obstack
1659 @var{obstack-ptr}.
1660 @end deftypefun
1662 @comment obstack.h
1663 @comment GNU
1664 @deftypefun void obstack_blank_fast (struct obstack *@var{obstack-ptr}, int @var{size})
1665 The function @code{obstack_blank_fast} adds @var{size} bytes to the
1666 growing object in obstack @var{obstack-ptr} without initializing them.
1667 @end deftypefun
1669 When you check for space using @code{obstack_room} and there is not
1670 enough room for what you want to add, the fast growth functions
1671 are not safe.  In this case, simply use the corresponding ordinary
1672 growth function instead.  Very soon this will copy the object to a
1673 new chunk; then there will be lots of room available again.
1675 So, each time you use an ordinary growth function, check afterward for
1676 sufficient space using @code{obstack_room}.  Once the object is copied
1677 to a new chunk, there will be plenty of space again, so the program will
1678 start using the fast growth functions again.
1680 Here is an example:
1682 @smallexample
1683 @group
1684 void
1685 add_string (struct obstack *obstack, const char *ptr, int len)
1687   while (len > 0)
1688     @{
1689       int room = obstack_room (obstack);
1690       if (room == 0)
1691         @{
1692           /* @r{Not enough room. Add one character slowly,}
1693              @r{which may copy to a new chunk and make room.}  */
1694           obstack_1grow (obstack, *ptr++);
1695           len--;
1696         @}
1697       else
1698         @{
1699           if (room > len)
1700             room = len;
1701           /* @r{Add fast as much as we have room for.} */
1702           len -= room;
1703           while (room-- > 0)
1704             obstack_1grow_fast (obstack, *ptr++);
1705         @}
1706     @}
1708 @end group
1709 @end smallexample
1711 @node Status of an Obstack
1712 @subsection Status of an Obstack
1713 @cindex obstack status
1714 @cindex status of obstack
1716 Here are functions that provide information on the current status of
1717 allocation in an obstack.  You can use them to learn about an object while
1718 still growing it.
1720 @comment obstack.h
1721 @comment GNU
1722 @deftypefun {void *} obstack_base (struct obstack *@var{obstack-ptr})
1723 This function returns the tentative address of the beginning of the
1724 currently growing object in @var{obstack-ptr}.  If you finish the object
1725 immediately, it will have that address.  If you make it larger first, it
1726 may outgrow the current chunk---then its address will change!
1728 If no object is growing, this value says where the next object you
1729 allocate will start (once again assuming it fits in the current
1730 chunk).
1731 @end deftypefun
1733 @comment obstack.h
1734 @comment GNU
1735 @deftypefun {void *} obstack_next_free (struct obstack *@var{obstack-ptr})
1736 This function returns the address of the first free byte in the current
1737 chunk of obstack @var{obstack-ptr}.  This is the end of the currently
1738 growing object.  If no object is growing, @code{obstack_next_free}
1739 returns the same value as @code{obstack_base}.
1740 @end deftypefun
1742 @comment obstack.h
1743 @comment GNU
1744 @deftypefun int obstack_object_size (struct obstack *@var{obstack-ptr})
1745 This function returns the size in bytes of the currently growing object.
1746 This is equivalent to
1748 @smallexample
1749 obstack_next_free (@var{obstack-ptr}) - obstack_base (@var{obstack-ptr})
1750 @end smallexample
1751 @end deftypefun
1753 @node Obstacks Data Alignment
1754 @subsection Alignment of Data in Obstacks
1755 @cindex alignment (in obstacks)
1757 Each obstack has an @dfn{alignment boundary}; each object allocated in
1758 the obstack automatically starts on an address that is a multiple of the
1759 specified boundary.  By default, this boundary is 4 bytes.
1761 To access an obstack's alignment boundary, use the macro
1762 @code{obstack_alignment_mask}, whose function prototype looks like
1763 this:
1765 @comment obstack.h
1766 @comment GNU
1767 @deftypefn Macro int obstack_alignment_mask (struct obstack *@var{obstack-ptr})
1768 The value is a bit mask; a bit that is 1 indicates that the corresponding
1769 bit in the address of an object should be 0.  The mask value should be one
1770 less than a power of 2; the effect is that all object addresses are
1771 multiples of that power of 2.  The default value of the mask is 3, so that
1772 addresses are multiples of 4.  A mask value of 0 means an object can start
1773 on any multiple of 1 (that is, no alignment is required).
1775 The expansion of the macro @code{obstack_alignment_mask} is an lvalue,
1776 so you can alter the mask by assignment.  For example, this statement:
1778 @smallexample
1779 obstack_alignment_mask (obstack_ptr) = 0;
1780 @end smallexample
1782 @noindent
1783 has the effect of turning off alignment processing in the specified obstack.
1784 @end deftypefn
1786 Note that a change in alignment mask does not take effect until
1787 @emph{after} the next time an object is allocated or finished in the
1788 obstack.  If you are not growing an object, you can make the new
1789 alignment mask take effect immediately by calling @code{obstack_finish}.
1790 This will finish a zero-length object and then do proper alignment for
1791 the next object.
1793 @node Obstack Chunks
1794 @subsection Obstack Chunks
1795 @cindex efficiency of chunks
1796 @cindex chunks
1798 Obstacks work by allocating space for themselves in large chunks, and
1799 then parceling out space in the chunks to satisfy your requests.  Chunks
1800 are normally 4096 bytes long unless you specify a different chunk size.
1801 The chunk size includes 8 bytes of overhead that are not actually used
1802 for storing objects.  Regardless of the specified size, longer chunks
1803 will be allocated when necessary for long objects.
1805 The obstack library allocates chunks by calling the function
1806 @code{obstack_chunk_alloc}, which you must define.  When a chunk is no
1807 longer needed because you have freed all the objects in it, the obstack
1808 library frees the chunk by calling @code{obstack_chunk_free}, which you
1809 must also define.
1811 These two must be defined (as macros) or declared (as functions) in each
1812 source file that uses @code{obstack_init} (@pxref{Creating Obstacks}).
1813 Most often they are defined as macros like this:
1815 @smallexample
1816 #define obstack_chunk_alloc malloc
1817 #define obstack_chunk_free free
1818 @end smallexample
1820 Note that these are simple macros (no arguments).  Macro definitions with
1821 arguments will not work!  It is necessary that @code{obstack_chunk_alloc}
1822 or @code{obstack_chunk_free}, alone, expand into a function name if it is
1823 not itself a function name.
1825 If you allocate chunks with @code{malloc}, the chunk size should be a
1826 power of 2.  The default chunk size, 4096, was chosen because it is long
1827 enough to satisfy many typical requests on the obstack yet short enough
1828 not to waste too much memory in the portion of the last chunk not yet used.
1830 @comment obstack.h
1831 @comment GNU
1832 @deftypefn Macro int obstack_chunk_size (struct obstack *@var{obstack-ptr})
1833 This returns the chunk size of the given obstack.
1834 @end deftypefn
1836 Since this macro expands to an lvalue, you can specify a new chunk size by
1837 assigning it a new value.  Doing so does not affect the chunks already
1838 allocated, but will change the size of chunks allocated for that particular
1839 obstack in the future.  It is unlikely to be useful to make the chunk size
1840 smaller, but making it larger might improve efficiency if you are
1841 allocating many objects whose size is comparable to the chunk size.  Here
1842 is how to do so cleanly:
1844 @smallexample
1845 if (obstack_chunk_size (obstack_ptr) < @var{new-chunk-size})
1846   obstack_chunk_size (obstack_ptr) = @var{new-chunk-size};
1847 @end smallexample
1849 @node Summary of Obstacks
1850 @subsection Summary of Obstack Functions
1852 Here is a summary of all the functions associated with obstacks.  Each
1853 takes the address of an obstack (@code{struct obstack *}) as its first
1854 argument.
1856 @table @code
1857 @item void obstack_init (struct obstack *@var{obstack-ptr})
1858 Initialize use of an obstack.  @xref{Creating Obstacks}.
1860 @item void *obstack_alloc (struct obstack *@var{obstack-ptr}, int @var{size})
1861 Allocate an object of @var{size} uninitialized bytes.
1862 @xref{Allocation in an Obstack}.
1864 @item void *obstack_copy (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1865 Allocate an object of @var{size} bytes, with contents copied from
1866 @var{address}.  @xref{Allocation in an Obstack}.
1868 @item void *obstack_copy0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1869 Allocate an object of @var{size}+1 bytes, with @var{size} of them copied
1870 from @var{address}, followed by a null character at the end.
1871 @xref{Allocation in an Obstack}.
1873 @item void obstack_free (struct obstack *@var{obstack-ptr}, void *@var{object})
1874 Free @var{object} (and everything allocated in the specified obstack
1875 more recently than @var{object}).  @xref{Freeing Obstack Objects}.
1877 @item void obstack_blank (struct obstack *@var{obstack-ptr}, int @var{size})
1878 Add @var{size} uninitialized bytes to a growing object.
1879 @xref{Growing Objects}.
1881 @item void obstack_grow (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1882 Add @var{size} bytes, copied from @var{address}, to a growing object.
1883 @xref{Growing Objects}.
1885 @item void obstack_grow0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1886 Add @var{size} bytes, copied from @var{address}, to a growing object,
1887 and then add another byte containing a null character.  @xref{Growing
1888 Objects}.
1890 @item void obstack_1grow (struct obstack *@var{obstack-ptr}, char @var{data-char})
1891 Add one byte containing @var{data-char} to a growing object.
1892 @xref{Growing Objects}.
1894 @item void *obstack_finish (struct obstack *@var{obstack-ptr})
1895 Finalize the object that is growing and return its permanent address.
1896 @xref{Growing Objects}.
1898 @item int obstack_object_size (struct obstack *@var{obstack-ptr})
1899 Get the current size of the currently growing object.  @xref{Growing
1900 Objects}.
1902 @item void obstack_blank_fast (struct obstack *@var{obstack-ptr}, int @var{size})
1903 Add @var{size} uninitialized bytes to a growing object without checking
1904 that there is enough room.  @xref{Extra Fast Growing}.
1906 @item void obstack_1grow_fast (struct obstack *@var{obstack-ptr}, char @var{data-char})
1907 Add one byte containing @var{data-char} to a growing object without
1908 checking that there is enough room.  @xref{Extra Fast Growing}.
1910 @item int obstack_room (struct obstack *@var{obstack-ptr})
1911 Get the amount of room now available for growing the current object.
1912 @xref{Extra Fast Growing}.
1914 @item int obstack_alignment_mask (struct obstack *@var{obstack-ptr})
1915 The mask used for aligning the beginning of an object.  This is an
1916 lvalue.  @xref{Obstacks Data Alignment}.
1918 @item int obstack_chunk_size (struct obstack *@var{obstack-ptr})
1919 The size for allocating chunks.  This is an lvalue.  @xref{Obstack Chunks}.
1921 @item void *obstack_base (struct obstack *@var{obstack-ptr})
1922 Tentative starting address of the currently growing object.
1923 @xref{Status of an Obstack}.
1925 @item void *obstack_next_free (struct obstack *@var{obstack-ptr})
1926 Address just after the end of the currently growing object.
1927 @xref{Status of an Obstack}.
1928 @end table
1930 @node Variable Size Automatic
1931 @section Automatic Storage with Variable Size
1932 @cindex automatic freeing
1933 @cindex @code{alloca} function
1934 @cindex automatic storage with variable size
1936 The function @code{alloca} supports a kind of half-dynamic allocation in
1937 which blocks are allocated dynamically but freed automatically.
1939 Allocating a block with @code{alloca} is an explicit action; you can
1940 allocate as many blocks as you wish, and compute the size at run time.  But
1941 all the blocks are freed when you exit the function that @code{alloca} was
1942 called from, just as if they were automatic variables declared in that
1943 function.  There is no way to free the space explicitly.
1945 The prototype for @code{alloca} is in @file{stdlib.h}.  This function is
1946 a BSD extension.
1947 @pindex stdlib.h
1949 @comment stdlib.h
1950 @comment GNU, BSD
1951 @deftypefun {void *} alloca (size_t @var{size});
1952 The return value of @code{alloca} is the address of a block of @var{size}
1953 bytes of storage, allocated in the stack frame of the calling function.
1954 @end deftypefun
1956 Do not use @code{alloca} inside the arguments of a function call---you
1957 will get unpredictable results, because the stack space for the
1958 @code{alloca} would appear on the stack in the middle of the space for
1959 the function arguments.  An example of what to avoid is @code{foo (x,
1960 alloca (4), y)}.
1961 @c This might get fixed in future versions of GCC, but that won't make
1962 @c it safe with compilers generally.
1964 @menu
1965 * Alloca Example::              Example of using @code{alloca}.
1966 * Advantages of Alloca::        Reasons to use @code{alloca}.
1967 * Disadvantages of Alloca::     Reasons to avoid @code{alloca}.
1968 * GNU C Variable-Size Arrays::  Only in GNU C, here is an alternative
1969                                  method of allocating dynamically and
1970                                  freeing automatically.
1971 @end menu
1973 @node Alloca Example
1974 @subsection @code{alloca} Example
1976 As an example of use of @code{alloca}, here is a function that opens a file
1977 name made from concatenating two argument strings, and returns a file
1978 descriptor or minus one signifying failure:
1980 @smallexample
1982 open2 (char *str1, char *str2, int flags, int mode)
1984   char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
1985   stpcpy (stpcpy (name, str1), str2);
1986   return open (name, flags, mode);
1988 @end smallexample
1990 @noindent
1991 Here is how you would get the same results with @code{malloc} and
1992 @code{free}:
1994 @smallexample
1996 open2 (char *str1, char *str2, int flags, int mode)
1998   char *name = (char *) malloc (strlen (str1) + strlen (str2) + 1);
1999   int desc;
2000   if (name == 0)
2001     fatal ("virtual memory exceeded");
2002   stpcpy (stpcpy (name, str1), str2);
2003   desc = open (name, flags, mode);
2004   free (name);
2005   return desc;
2007 @end smallexample
2009 As you can see, it is simpler with @code{alloca}.  But @code{alloca} has
2010 other, more important advantages, and some disadvantages.
2012 @node Advantages of Alloca
2013 @subsection Advantages of @code{alloca}
2015 Here are the reasons why @code{alloca} may be preferable to @code{malloc}:
2017 @itemize @bullet
2018 @item
2019 Using @code{alloca} wastes very little space and is very fast.  (It is
2020 open-coded by the GNU C compiler.)
2022 @item
2023 Since @code{alloca} does not have separate pools for different sizes of
2024 block, space used for any size block can be reused for any other size.
2025 @code{alloca} does not cause storage fragmentation.
2027 @item
2028 @cindex longjmp
2029 Nonlocal exits done with @code{longjmp} (@pxref{Non-Local Exits})
2030 automatically free the space allocated with @code{alloca} when they exit
2031 through the function that called @code{alloca}.  This is the most
2032 important reason to use @code{alloca}.
2034 To illustrate this, suppose you have a function
2035 @code{open_or_report_error} which returns a descriptor, like
2036 @code{open}, if it succeeds, but does not return to its caller if it
2037 fails.  If the file cannot be opened, it prints an error message and
2038 jumps out to the command level of your program using @code{longjmp}.
2039 Let's change @code{open2} (@pxref{Alloca Example}) to use this
2040 subroutine:@refill
2042 @smallexample
2044 open2 (char *str1, char *str2, int flags, int mode)
2046   char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
2047   stpcpy (stpcpy (name, str1), str2);
2048   return open_or_report_error (name, flags, mode);
2050 @end smallexample
2052 @noindent
2053 Because of the way @code{alloca} works, the storage it allocates is
2054 freed even when an error occurs, with no special effort required.
2056 By contrast, the previous definition of @code{open2} (which uses
2057 @code{malloc} and @code{free}) would develop a storage leak if it were
2058 changed in this way.  Even if you are willing to make more changes to
2059 fix it, there is no easy way to do so.
2060 @end itemize
2062 @node Disadvantages of Alloca
2063 @subsection Disadvantages of @code{alloca}
2065 @cindex @code{alloca} disadvantages
2066 @cindex disadvantages of @code{alloca}
2067 These are the disadvantages of @code{alloca} in comparison with
2068 @code{malloc}:
2070 @itemize @bullet
2071 @item
2072 If you try to allocate more storage than the machine can provide, you
2073 don't get a clean error message.  Instead you get a fatal signal like
2074 the one you would get from an infinite recursion; probably a
2075 segmentation violation (@pxref{Program Error Signals}).
2077 @item
2078 Some non-GNU systems fail to support @code{alloca}, so it is less
2079 portable.  However, a slower emulation of @code{alloca} written in C
2080 is available for use on systems with this deficiency.
2081 @end itemize
2083 @node GNU C Variable-Size Arrays
2084 @subsection GNU C Variable-Size Arrays
2085 @cindex variable-sized arrays
2087 In GNU C, you can replace most uses of @code{alloca} with an array of
2088 variable size.  Here is how @code{open2} would look then:
2090 @smallexample
2091 int open2 (char *str1, char *str2, int flags, int mode)
2093   char name[strlen (str1) + strlen (str2) + 1];
2094   stpcpy (stpcpy (name, str1), str2);
2095   return open (name, flags, mode);
2097 @end smallexample
2099 But @code{alloca} is not always equivalent to a variable-sized array, for
2100 several reasons:
2102 @itemize @bullet
2103 @item
2104 A variable size array's space is freed at the end of the scope of the
2105 name of the array.  The space allocated with @code{alloca}
2106 remains until the end of the function.
2108 @item
2109 It is possible to use @code{alloca} within a loop, allocating an
2110 additional block on each iteration.  This is impossible with
2111 variable-sized arrays.
2112 @end itemize
2114 @strong{Note:} If you mix use of @code{alloca} and variable-sized arrays
2115 within one function, exiting a scope in which a variable-sized array was
2116 declared frees all blocks allocated with @code{alloca} during the
2117 execution of that scope.
2119 @ignore
2120 @c This was never actually implemented.  -zw
2121 @node Relocating Allocator
2122 @section Relocating Allocator
2124 @cindex relocating memory allocator
2125 Any system of dynamic memory allocation has overhead: the amount of
2126 space it uses is more than the amount the program asks for.  The
2127 @dfn{relocating memory allocator} achieves very low overhead by moving
2128 blocks in memory as necessary, on its own initiative.
2130 @c @menu
2131 @c * Relocator Concepts::               How to understand relocating allocation.
2132 @c * Using Relocator::          Functions for relocating allocation.
2133 @c @end menu
2135 @node Relocator Concepts
2136 @subsection Concepts of Relocating Allocation
2138 @ifinfo
2139 The @dfn{relocating memory allocator} achieves very low overhead by
2140 moving blocks in memory as necessary, on its own initiative.
2141 @end ifinfo
2143 When you allocate a block with @code{malloc}, the address of the block
2144 never changes unless you use @code{realloc} to change its size.  Thus,
2145 you can safely store the address in various places, temporarily or
2146 permanently, as you like.  This is not safe when you use the relocating
2147 memory allocator, because any and all relocatable blocks can move
2148 whenever you allocate memory in any fashion.  Even calling @code{malloc}
2149 or @code{realloc} can move the relocatable blocks.
2151 @cindex handle
2152 For each relocatable block, you must make a @dfn{handle}---a pointer
2153 object in memory, designated to store the address of that block.  The
2154 relocating allocator knows where each block's handle is, and updates the
2155 address stored there whenever it moves the block, so that the handle
2156 always points to the block.  Each time you access the contents of the
2157 block, you should fetch its address anew from the handle.
2159 To call any of the relocating allocator functions from a signal handler
2160 is almost certainly incorrect, because the signal could happen at any
2161 time and relocate all the blocks.  The only way to make this safe is to
2162 block the signal around any access to the contents of any relocatable
2163 block---not a convenient mode of operation.  @xref{Nonreentrancy}.
2165 @node Using Relocator
2166 @subsection Allocating and Freeing Relocatable Blocks
2168 @pindex malloc.h
2169 In the descriptions below, @var{handleptr} designates the address of the
2170 handle.  All the functions are declared in @file{malloc.h}; all are GNU
2171 extensions.
2173 @comment malloc.h
2174 @comment GNU
2175 @c @deftypefun {void *} r_alloc (void **@var{handleptr}, size_t @var{size})
2176 This function allocates a relocatable block of size @var{size}.  It
2177 stores the block's address in @code{*@var{handleptr}} and returns
2178 a non-null pointer to indicate success.
2180 If @code{r_alloc} can't get the space needed, it stores a null pointer
2181 in @code{*@var{handleptr}}, and returns a null pointer.
2182 @end deftypefun
2184 @comment malloc.h
2185 @comment GNU
2186 @c @deftypefun void r_alloc_free (void **@var{handleptr})
2187 This function is the way to free a relocatable block.  It frees the
2188 block that @code{*@var{handleptr}} points to, and stores a null pointer
2189 in @code{*@var{handleptr}} to show it doesn't point to an allocated
2190 block any more.
2191 @end deftypefun
2193 @comment malloc.h
2194 @comment GNU
2195 @c @deftypefun {void *} r_re_alloc (void **@var{handleptr}, size_t @var{size})
2196 The function @code{r_re_alloc} adjusts the size of the block that
2197 @code{*@var{handleptr}} points to, making it @var{size} bytes long.  It
2198 stores the address of the resized block in @code{*@var{handleptr}} and
2199 returns a non-null pointer to indicate success.
2201 If enough memory is not available, this function returns a null pointer
2202 and does not modify @code{*@var{handleptr}}.
2203 @end deftypefun
2204 @end ignore
2206 @ignore
2207 @comment No longer available...
2209 @comment @node Memory Warnings
2210 @comment @section Memory Usage Warnings
2211 @comment @cindex memory usage warnings
2212 @comment @cindex warnings of memory almost full
2214 @pindex malloc.c
2215 You can ask for warnings as the program approaches running out of memory
2216 space, by calling @code{memory_warnings}.  This tells @code{malloc} to
2217 check memory usage every time it asks for more memory from the operating
2218 system.  This is a GNU extension declared in @file{malloc.h}.
2220 @comment malloc.h
2221 @comment GNU
2222 @comment @deftypefun void memory_warnings (void *@var{start}, void (*@var{warn-func}) (const char *))
2223 Call this function to request warnings for nearing exhaustion of virtual
2224 memory.
2226 The argument @var{start} says where data space begins, in memory.  The
2227 allocator compares this against the last address used and against the
2228 limit of data space, to determine the fraction of available memory in
2229 use.  If you supply zero for @var{start}, then a default value is used
2230 which is right in most circumstances.
2232 For @var{warn-func}, supply a function that @code{malloc} can call to
2233 warn you.  It is called with a string (a warning message) as argument.
2234 Normally it ought to display the string for the user to read.
2235 @end deftypefun
2237 The warnings come when memory becomes 75% full, when it becomes 85%
2238 full, and when it becomes 95% full.  Above 95% you get another warning
2239 each time memory usage increases.
2241 @end ignore