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