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