1 @comment !!! describe mmap et al (here?)
4 @node Memory Allocation, Character Handling, Error Reporting, Top
5 @chapter Memory Allocation
6 @cindex memory allocation
7 @cindex storage allocation
9 The GNU system provides several methods for allocating memory space
10 under explicit program control. They vary in generality and in
16 The @code{malloc} facility allows fully general dynamic allocation.
17 @xref{Unconstrained Allocation}.
20 Obstacks are another facility, less general than @code{malloc} but more
21 efficient and convenient for stacklike allocation. @xref{Obstacks}.
24 The function @code{alloca} lets you allocate storage dynamically that
25 will be freed automatically. @xref{Variable Size Automatic}.
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
34 * Obstacks:: Obstacks are less general than malloc
35 but more efficient and convenient.
36 * Variable Size Automatic:: Allocation of variable-sized blocks
37 of automatic storage that are freed when the
38 calling function returns.
39 * Relocating Allocator:: Waste less memory, if you can tolerate
40 automatic relocation of the blocks you get.
41 * Memory Warnings:: Getting warnings when memory is nearly full.
45 @section Dynamic Memory Allocation Concepts
46 @cindex dynamic allocation
47 @cindex static allocation
48 @cindex automatic allocation
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.
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
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.
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.
70 @node Dynamic Allocation and C
71 @section Dynamic Allocation and C
73 The C language supports two kinds of memory allocation through the variables
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.
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.
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.
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 use dynamic allocation only
100 when neither static nor automatic allocation will serve.
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:
112 = (struct foobar *) malloc (sizeof (struct foobar));
114 ptr->next = current_foobar;
115 current_foobar = ptr;
119 @node Unconstrained Allocation
120 @section Unconstrained Allocation
121 @cindex unconstrained storage allocation
122 @cindex @code{malloc} function
123 @cindex heap, dynamic allocation from
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
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
137 * Allocating Cleared Space:: Use @code{calloc} to allocate a
139 * Efficiency and Malloc:: Efficiency considerations in use of
141 * Aligned Memory Blocks:: Allocating specially aligned memory:
142 @code{memalign} and @code{valloc}.
143 * Heap Consistency Checking:: Automatic checking for errors.
144 * Hooks for Malloc:: You can use these hooks for debugging
145 programs that use @code{malloc}.
146 * Statistics of Malloc:: Getting information about how much
147 memory your program is using.
148 * Summary of Malloc:: Summary of @code{malloc} and related functions.
151 @node Basic Allocation
152 @subsection Basic Storage Allocation
153 @cindex allocation of memory with @code{malloc}
155 To allocate a block of memory, call @code{malloc}. The prototype for
156 this function is in @file{stdlib.h}.
159 @comment malloc.h stdlib.h
161 @deftypefun {void *} malloc (size_t @var{size})
162 This function returns a pointer to a newly allocated block @var{size}
163 bytes long, or a null pointer if the block could not be allocated.
166 The contents of the block are undefined; you must initialize it yourself
167 (or use @code{calloc} instead; @pxref{Allocating Cleared Space}).
168 Normally you would cast the value as a pointer to the kind of object
169 that you want to store in the block. Here we show an example of doing
170 so, and of initializing the space with zeros using the library function
171 @code{memset} (@pxref{Copying and Concatenation}):
176 ptr = (struct foo *) malloc (sizeof (struct foo));
177 if (ptr == 0) abort ();
178 memset (ptr, 0, sizeof (struct foo));
181 You can store the result of @code{malloc} into any pointer variable
182 without a cast, because ANSI C automatically converts the type
183 @code{void *} to another type of pointer when necessary. But the cast
184 is necessary in contexts other than assignment operators or if you might
185 want your code to run in traditional C.
187 Remember that when allocating space for a string, the argument to
188 @code{malloc} must be one plus the length of the string. This is
189 because a string is terminated with a null character that doesn't count
190 in the ``length'' of the string but does need space. For example:
195 ptr = (char *) malloc (length + 1);
199 @xref{Representation of Strings}, for more information about this.
201 @node Malloc Examples
202 @subsection Examples of @code{malloc}
204 If no more space is available, @code{malloc} returns a null pointer.
205 You should check the value of @emph{every} call to @code{malloc}. It is
206 useful to write a subroutine that calls @code{malloc} and reports an
207 error if the value is a null pointer, returning only if the value is
208 nonzero. This function is conventionally called @code{xmalloc}. Here
213 xmalloc (size_t size)
215 register void *value = malloc (size);
217 fatal ("virtual memory exhausted");
222 Here is a real example of using @code{malloc} (by way of @code{xmalloc}).
223 The function @code{savestring} will copy a sequence of characters into
224 a newly allocated null-terminated string:
228 savestring (const char *ptr, size_t len)
230 register char *value = (char *) xmalloc (len + 1);
231 memcpy (value, ptr, len);
237 The block that @code{malloc} gives you is guaranteed to be aligned so
238 that it can hold any type of data. In the GNU system, the address is
239 always a multiple of eight; if the size of block is 16 or more, then the
240 address is always a multiple of 16. Only rarely is any higher boundary
241 (such as a page boundary) necessary; for those cases, use
242 @code{memalign} or @code{valloc} (@pxref{Aligned Memory Blocks}).
244 Note that the memory located after the end of the block is likely to be
245 in use for something else; perhaps a block already allocated by another
246 call to @code{malloc}. If you attempt to treat the block as longer than
247 you asked for it to be, you are liable to destroy the data that
248 @code{malloc} uses to keep track of its blocks, or you may destroy the
249 contents of another block. If you have already allocated a block and
250 discover you want it to be bigger, use @code{realloc} (@pxref{Changing
253 @node Freeing after Malloc
254 @subsection Freeing Memory Allocated with @code{malloc}
255 @cindex freeing memory allocated with @code{malloc}
256 @cindex heap, freeing memory from
258 When you no longer need a block that you got with @code{malloc}, use the
259 function @code{free} to make the block available to be allocated again.
260 The prototype for this function is in @file{stdlib.h}.
263 @comment malloc.h stdlib.h
265 @deftypefun void free (void *@var{ptr})
266 The @code{free} function deallocates the block of storage pointed at
272 @deftypefun void cfree (void *@var{ptr})
273 This function does the same thing as @code{free}. It's provided for
274 backward compatibility with SunOS; you should use @code{free} instead.
277 Freeing a block alters the contents of the block. @strong{Do not expect to
278 find any data (such as a pointer to the next block in a chain of blocks) in
279 the block after freeing it.} Copy whatever you need out of the block before
280 freeing it! Here is an example of the proper way to free all the blocks in
281 a chain, and the strings that they point to:
291 free_chain (struct chain *chain)
295 struct chain *next = chain->next;
303 Occasionally, @code{free} can actually return memory to the operating
304 system and make the process smaller. Usually, all it can do is allow a
305 later call to @code{malloc} to reuse the space. In the meantime, the
306 space remains in your program as part of a free-list used internally by
309 There is no point in freeing blocks at the end of a program, because all
310 of the program's space is given back to the system when the process
313 @node Changing Block Size
314 @subsection Changing the Size of a Block
315 @cindex changing the size of a block (@code{malloc})
317 Often you do not know for certain how big a block you will ultimately need
318 at the time you must begin to use the block. For example, the block might
319 be a buffer that you use to hold a line being read from a file; no matter
320 how long you make the buffer initially, you may encounter a line that is
323 You can make the block longer by calling @code{realloc}. This function
324 is declared in @file{stdlib.h}.
327 @comment malloc.h stdlib.h
329 @deftypefun {void *} realloc (void *@var{ptr}, size_t @var{newsize})
330 The @code{realloc} function changes the size of the block whose address is
331 @var{ptr} to be @var{newsize}.
333 Since the space after the end of the block may be in use, @code{realloc}
334 may find it necessary to copy the block to a new address where more free
335 space is available. The value of @code{realloc} is the new address of the
336 block. If the block needs to be moved, @code{realloc} copies the old
339 If you pass a null pointer for @var{ptr}, @code{realloc} behaves just
340 like @samp{malloc (@var{newsize})}. This can be convenient, but beware
341 that older implementations (before ANSI C) may not support this
342 behavior, and will probably crash when @code{realloc} is passed a null
346 Like @code{malloc}, @code{realloc} may return a null pointer if no
347 memory space is available to make the block bigger. When this happens,
348 the original block is untouched; it has not been modified or relocated.
350 In most cases it makes no difference what happens to the original block
351 when @code{realloc} fails, because the application program cannot continue
352 when it is out of memory, and the only thing to do is to give a fatal error
353 message. Often it is convenient to write and use a subroutine,
354 conventionally called @code{xrealloc}, that takes care of the error message
355 as @code{xmalloc} does for @code{malloc}:
359 xrealloc (void *ptr, size_t size)
361 register void *value = realloc (ptr, size);
363 fatal ("Virtual memory exhausted");
368 You can also use @code{realloc} to make a block smaller. The reason you
369 would do this is to avoid tying up a lot of memory space when only a little
370 is needed. Making a block smaller sometimes necessitates copying it, so it
371 can fail if no other space is available.
373 If the new size you specify is the same as the old size, @code{realloc}
374 is guaranteed to change nothing and return the same address that you gave.
376 @node Allocating Cleared Space
377 @subsection Allocating Cleared Space
379 The function @code{calloc} allocates memory and clears it to zero. It
380 is declared in @file{stdlib.h}.
383 @comment malloc.h stdlib.h
385 @deftypefun {void *} calloc (size_t @var{count}, size_t @var{eltsize})
386 This function allocates a block long enough to contain a vector of
387 @var{count} elements, each of size @var{eltsize}. Its contents are
388 cleared to zero before @code{calloc} returns.
391 You could define @code{calloc} as follows:
395 calloc (size_t count, size_t eltsize)
397 size_t size = count * eltsize;
398 void *value = malloc (size);
400 memset (value, 0, size);
405 We rarely use @code{calloc} today, because it is equivalent to such a
406 simple combination of other features that are more often used. It is a
407 historical holdover that is not quite obsolete.
409 @node Efficiency and Malloc
410 @subsection Efficiency Considerations for @code{malloc}
411 @cindex efficiency and @code{malloc}
413 To make the best use of @code{malloc}, it helps to know that the GNU
414 version of @code{malloc} always dispenses small amounts of memory in
415 blocks whose sizes are powers of two. It keeps separate pools for each
416 power of two. This holds for sizes up to a page size. Therefore, if
417 you are free to choose the size of a small block in order to make
418 @code{malloc} more efficient, make it a power of two.
419 @c !!! xref getpagesize
421 Once a page is split up for a particular block size, it can't be reused
422 for another size unless all the blocks in it are freed. In many
423 programs, this is unlikely to happen. Thus, you can sometimes make a
424 program use memory more efficiently by using blocks of the same size for
425 many different purposes.
427 When you ask for memory blocks of a page or larger, @code{malloc} uses a
428 different strategy; it rounds the size up to a multiple of a page, and
429 it can coalesce and split blocks as needed.
431 The reason for the two strategies is that it is important to allocate
432 and free small blocks as fast as possible, but speed is less important
433 for a large block since the program normally spends a fair amount of
434 time using it. Also, large blocks are normally fewer in number.
435 Therefore, for large blocks, it makes sense to use a method which takes
436 more time to minimize the wasted space.
438 @node Aligned Memory Blocks
439 @subsection Allocating Aligned Memory Blocks
441 @cindex page boundary
442 @cindex alignment (with @code{malloc})
444 The address of a block returned by @code{malloc} or @code{realloc} in
445 the GNU system is always a multiple of eight. If you need a block whose
446 address is a multiple of a higher power of two than that, use
447 @code{memalign} or @code{valloc}. These functions are declared in
450 With the GNU library, you can use @code{free} to free the blocks that
451 @code{memalign} and @code{valloc} return. That does not work in BSD,
452 however---BSD does not provide any way to free such blocks.
454 @comment malloc.h stdlib.h
456 @deftypefun {void *} memalign (size_t @var{size}, size_t @var{boundary})
457 The @code{memalign} function allocates a block of @var{size} bytes whose
458 address is a multiple of @var{boundary}. The @var{boundary} must be a
459 power of two! The function @code{memalign} works by calling
460 @code{malloc} to allocate a somewhat larger block, and then returning an
461 address within the block that is on the specified boundary.
464 @comment malloc.h stdlib.h
466 @deftypefun {void *} valloc (size_t @var{size})
467 Using @code{valloc} is like using @code{memalign} and passing the page size
468 as the value of the second argument. It is implemented like this:
474 return memalign (size, getpagesize ());
477 @c !!! xref getpagesize
480 @node Heap Consistency Checking
481 @subsection Heap Consistency Checking
483 @cindex heap consistency checking
484 @cindex consistency checking, of heap
486 You can ask @code{malloc} to check the consistency of dynamic storage by
487 using the @code{mcheck} function. This function is a GNU extension,
488 declared in @file{malloc.h}.
493 @deftypefun int mcheck (void (*@var{abortfn}) (enum mcheck_status @var{status}))
494 Calling @code{mcheck} tells @code{malloc} to perform occasional
495 consistency checks. These will catch things such as writing
496 past the end of a block that was allocated with @code{malloc}.
498 The @var{abortfn} argument is the function to call when an inconsistency
499 is found. If you supply a null pointer, then @code{mcheck} uses a
500 default function which prints a message and calls @code{abort}
501 (@pxref{Aborting a Program}). The function you supply is called with
502 one argument, which says what sort of inconsistency was detected; its
503 type is described below.
505 It is too late to begin allocation checking once you have allocated
506 anything with @code{malloc}. So @code{mcheck} does nothing in that
507 case. The function returns @code{-1} if you call it too late, and
508 @code{0} otherwise (when it is successful).
510 The easiest way to arrange to call @code{mcheck} early enough is to use
511 the option @samp{-lmcheck} when you link your program; then you don't
512 need to modify your program source at all.
515 @deftypefun {enum mcheck_status} mprobe (void *@var{pointer})
516 The @code{mprobe} function lets you explicitly check for inconsistencies
517 in a particular allocated block. You must have already called
518 @code{mcheck} at the beginning of the program, to do its occasional
519 checks; calling @code{mprobe} requests an additional consistency check
520 to be done at the time of the call.
522 The argument @var{pointer} must be a pointer returned by @code{malloc}
523 or @code{realloc}. @code{mprobe} returns a value that says what
524 inconsistency, if any, was found. The values are described below.
527 @deftp {Data Type} {enum mcheck_status}
528 This enumerated type describes what kind of inconsistency was detected
529 in an allocated block, if any. Here are the possible values:
532 @item MCHECK_DISABLED
533 @code{mcheck} was not called before the first allocation.
534 No consistency checking can be done.
536 No inconsistency detected.
538 The data immediately before the block was modified.
539 This commonly happens when an array index or pointer
540 is decremented too far.
542 The data immediately after the block was modified.
543 This commonly happens when an array index or pointer
544 is incremented too far.
546 The block was already freed.
550 @node Hooks for Malloc
551 @subsection Storage Allocation Hooks
552 @cindex allocation hooks, for @code{malloc}
554 The GNU C library lets you modify the behavior of @code{malloc},
555 @code{realloc}, and @code{free} by specifying appropriate hook
556 functions. You can use these hooks to help you debug programs that use
557 dynamic storage allocation, for example.
559 The hook variables are declared in @file{malloc.h}.
564 @defvar __malloc_hook
565 The value of this variable is a pointer to function that @code{malloc}
566 uses whenever it is called. You should define this function to look
567 like @code{malloc}; that is, like:
570 void *@var{function} (size_t @var{size})
576 @defvar __realloc_hook
577 The value of this variable is a pointer to function that @code{realloc}
578 uses whenever it is called. You should define this function to look
579 like @code{realloc}; that is, like:
582 void *@var{function} (void *@var{ptr}, size_t @var{size})
589 The value of this variable is a pointer to function that @code{free}
590 uses whenever it is called. You should define this function to look
591 like @code{free}; that is, like:
594 void @var{function} (void *@var{ptr})
598 You must make sure that the function you install as a hook for one of
599 these functions does not call that function recursively without restoring
600 the old value of the hook first! Otherwise, your program will get stuck
601 in an infinite recursion.
603 Here is an example showing how to use @code{__malloc_hook} properly. It
604 installs a function that prints out information every time @code{malloc}
608 static void *(*old_malloc_hook) (size_t);
610 my_malloc_hook (size_t size)
613 __malloc_hook = old_malloc_hook;
614 result = malloc (size);
615 __malloc_hook = my_malloc_hook;
616 printf ("malloc (%u) returns %p\n", (unsigned int) size, result);
623 old_malloc_hook = __malloc_hook;
624 __malloc_hook = my_malloc_hook;
629 The @code{mcheck} function (@pxref{Heap Consistency Checking}) works by
630 installing such hooks.
632 @c __morecore, __after_morecore_hook are undocumented
633 @c It's not clear whether to document them.
635 @node Statistics of Malloc
636 @subsection Statistics for Storage Allocation with @code{malloc}
638 @cindex allocation statistics
639 You can get information about dynamic storage allocation by calling the
640 @code{mstats} function. This function and its associated data type are
641 declared in @file{malloc.h}; they are a GNU extension.
646 @deftp {Data Type} {struct mstats}
647 This structure type is used to return information about the dynamic
648 storage allocator. It contains the following members:
651 @item size_t bytes_total
652 This is the total size of memory managed by @code{malloc}, in bytes.
654 @item size_t chunks_used
655 This is the number of chunks in use. (The storage allocator internally
656 gets chunks of memory from the operating system, and then carves them up
657 to satisfy individual @code{malloc} requests; see @ref{Efficiency and
660 @item size_t bytes_used
661 This is the number of bytes in use.
663 @item size_t chunks_free
664 This is the number of chunks which are free -- that is, that have been
665 allocated by the operating system to your program, but which are not
668 @item size_t bytes_free
669 This is the number of bytes which are free.
675 @deftypefun {struct mstats} mstats (void)
676 This function returns information about the current dynamic memory usage
677 in a structure of type @code{struct mstats}.
680 @node Summary of Malloc
681 @subsection Summary of @code{malloc}-Related Functions
683 Here is a summary of the functions that work with @code{malloc}:
686 @item void *malloc (size_t @var{size})
687 Allocate a block of @var{size} bytes. @xref{Basic Allocation}.
689 @item void free (void *@var{addr})
690 Free a block previously allocated by @code{malloc}. @xref{Freeing after
693 @item void *realloc (void *@var{addr}, size_t @var{size})
694 Make a block previously allocated by @code{malloc} larger or smaller,
695 possibly by copying it to a new location. @xref{Changing Block Size}.
697 @item void *calloc (size_t @var{count}, size_t @var{eltsize})
698 Allocate a block of @var{count} * @var{eltsize} bytes using
699 @code{malloc}, and set its contents to zero. @xref{Allocating Cleared
702 @item void *valloc (size_t @var{size})
703 Allocate a block of @var{size} bytes, starting on a page boundary.
704 @xref{Aligned Memory Blocks}.
706 @item void *memalign (size_t @var{size}, size_t @var{boundary})
707 Allocate a block of @var{size} bytes, starting on an address that is a
708 multiple of @var{boundary}. @xref{Aligned Memory Blocks}.
710 @item int mcheck (void (*@var{abortfn}) (void))
711 Tell @code{malloc} to perform occasional consistency checks on
712 dynamically allocated memory, and to call @var{abortfn} when an
713 inconsistency is found. @xref{Heap Consistency Checking}.
715 @item void *(*__malloc_hook) (size_t @var{size})
716 A pointer to a function that @code{malloc} uses whenever it is called.
718 @item void *(*__realloc_hook) (void *@var{ptr}, size_t @var{size})
719 A pointer to a function that @code{realloc} uses whenever it is called.
721 @item void (*__free_hook) (void *@var{ptr})
722 A pointer to a function that @code{free} uses whenever it is called.
724 @item struct mstats mstats (void)
725 Return information about the current dynamic memory usage.
726 @xref{Statistics of Malloc}.
733 An @dfn{obstack} is a pool of memory containing a stack of objects. You
734 can create any number of separate obstacks, and then allocate objects in
735 specified obstacks. Within each obstack, the last object allocated must
736 always be the first one freed, but distinct obstacks are independent of
739 Aside from this one constraint of order of freeing, obstacks are totally
740 general: an obstack can contain any number of objects of any size. They
741 are implemented with macros, so allocation is usually very fast as long as
742 the objects are usually small. And the only space overhead per object is
743 the padding needed to start each object on a suitable boundary.
746 * Creating Obstacks:: How to declare an obstack in your program.
747 * Preparing for Obstacks:: Preparations needed before you can
749 * Allocation in an Obstack:: Allocating objects in an obstack.
750 * Freeing Obstack Objects:: Freeing objects in an obstack.
751 * Obstack Functions:: The obstack functions are both
752 functions and macros.
753 * Growing Objects:: Making an object bigger by stages.
754 * Extra Fast Growing:: Extra-high-efficiency (though more
755 complicated) growing objects.
756 * Status of an Obstack:: Inquiries about the status of an obstack.
757 * Obstacks Data Alignment:: Controlling alignment of objects in obstacks.
758 * Obstack Chunks:: How obstacks obtain and release chunks;
759 efficiency considerations.
760 * Summary of Obstacks::
763 @node Creating Obstacks
764 @subsection Creating Obstacks
766 The utilities for manipulating obstacks are declared in the header
767 file @file{obstack.h}.
772 @deftp {Data Type} {struct obstack}
773 An obstack is represented by a data structure of type @code{struct
774 obstack}. This structure has a small fixed size; it records the status
775 of the obstack and how to find the space in which objects are allocated.
776 It does not contain any of the objects themselves. You should not try
777 to access the contents of the structure directly; use only the functions
778 described in this chapter.
781 You can declare variables of type @code{struct obstack} and use them as
782 obstacks, or you can allocate obstacks dynamically like any other kind
783 of object. Dynamic allocation of obstacks allows your program to have a
784 variable number of different stacks. (You can even allocate an
785 obstack structure in another obstack, but this is rarely useful.)
787 All the functions that work with obstacks require you to specify which
788 obstack to use. You do this with a pointer of type @code{struct obstack
789 *}. In the following, we often say ``an obstack'' when strictly
790 speaking the object at hand is such a pointer.
792 The objects in the obstack are packed into large blocks called
793 @dfn{chunks}. The @code{struct obstack} structure points to a chain of
794 the chunks currently in use.
796 The obstack library obtains a new chunk whenever you allocate an object
797 that won't fit in the previous chunk. Since the obstack library manages
798 chunks automatically, you don't need to pay much attention to them, but
799 you do need to supply a function which the obstack library should use to
800 get a chunk. Usually you supply a function which uses @code{malloc}
801 directly or indirectly. You must also supply a function to free a chunk.
802 These matters are described in the following section.
804 @node Preparing for Obstacks
805 @subsection Preparing for Using Obstacks
807 Each source file in which you plan to use the obstack functions
808 must include the header file @file{obstack.h}, like this:
814 @findex obstack_chunk_alloc
815 @findex obstack_chunk_free
816 Also, if the source file uses the macro @code{obstack_init}, it must
817 declare or define two functions or macros that will be called by the
818 obstack library. One, @code{obstack_chunk_alloc}, is used to allocate
819 the chunks of memory into which objects are packed. The other,
820 @code{obstack_chunk_free}, is used to return chunks when the objects in
821 them are freed. These macros should appear before any use of obstacks
824 Usually these are defined to use @code{malloc} via the intermediary
825 @code{xmalloc} (@pxref{Unconstrained Allocation}). This is done with
826 the following pair of macro definitions:
829 #define obstack_chunk_alloc xmalloc
830 #define obstack_chunk_free free
834 Though the storage you get using obstacks really comes from @code{malloc},
835 using obstacks is faster because @code{malloc} is called less often, for
836 larger blocks of memory. @xref{Obstack Chunks}, for full details.
838 At run time, before the program can use a @code{struct obstack} object
839 as an obstack, it must initialize the obstack by calling
844 @deftypefun int obstack_init (struct obstack *@var{obstack-ptr})
845 Initialize obstack @var{obstack-ptr} for allocation of objects. This
846 function calls the obstack's @code{obstack_chunk_alloc} function. It
847 returns 0 if @code{obstack_chunk_alloc} returns a null pointer, meaning
848 that it is out of memory. Otherwise, it returns 1. If you supply an
849 @code{obstack_chunk_alloc} function that calls @code{exit}
850 (@pxref{Program Termination}) or @code{longjmp} (@pxref{Non-Local
851 Exits}) when out of memory, you can safely ignore the value that
852 @code{obstack_init} returns.
855 Here are two examples of how to allocate the space for an obstack and
856 initialize it. First, an obstack that is a static variable:
859 static struct obstack myobstack;
861 obstack_init (&myobstack);
865 Second, an obstack that is itself dynamically allocated:
868 struct obstack *myobstack_ptr
869 = (struct obstack *) xmalloc (sizeof (struct obstack));
871 obstack_init (myobstack_ptr);
874 @node Allocation in an Obstack
875 @subsection Allocation in an Obstack
876 @cindex allocation (obstacks)
878 The most direct way to allocate an object in an obstack is with
879 @code{obstack_alloc}, which is invoked almost like @code{malloc}.
883 @deftypefun {void *} obstack_alloc (struct obstack *@var{obstack-ptr}, int @var{size})
884 This allocates an uninitialized block of @var{size} bytes in an obstack
885 and returns its address. Here @var{obstack-ptr} specifies which obstack
886 to allocate the block in; it is the address of the @code{struct obstack}
887 object which represents the obstack. Each obstack function or macro
888 requires you to specify an @var{obstack-ptr} as the first argument.
890 This function calls the obstack's @code{obstack_chunk_alloc} function if
891 it needs to allocate a new chunk of memory; it returns a null pointer if
892 @code{obstack_chunk_alloc} returns one. In that case, it has not
893 changed the amount of memory allocated in the obstack. If you supply an
894 @code{obstack_chunk_alloc} function that calls @code{exit}
895 (@pxref{Program Termination}) or @code{longjmp} (@pxref{Non-Local
896 Exits}) when out of memory, then @code{obstack_alloc} will never return
900 For example, here is a function that allocates a copy of a string @var{str}
901 in a specific obstack, which is in the variable @code{string_obstack}:
904 struct obstack string_obstack;
907 copystring (char *string)
909 char *s = (char *) obstack_alloc (&string_obstack,
910 strlen (string) + 1);
911 memcpy (s, string, strlen (string));
916 To allocate a block with specified contents, use the function
917 @code{obstack_copy}, declared like this:
921 @deftypefun {void *} obstack_copy (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
922 This allocates a block and initializes it by copying @var{size}
923 bytes of data starting at @var{address}. It can return a null pointer
924 under the same conditions as @code{obstack_alloc}.
929 @deftypefun {void *} obstack_copy0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
930 Like @code{obstack_copy}, but appends an extra byte containing a null
931 character. This extra byte is not counted in the argument @var{size}.
934 The @code{obstack_copy0} function is convenient for copying a sequence
935 of characters into an obstack as a null-terminated string. Here is an
940 obstack_savestring (char *addr, int size)
942 return obstack_copy0 (&myobstack, addr, size);
947 Contrast this with the previous example of @code{savestring} using
948 @code{malloc} (@pxref{Basic Allocation}).
950 @node Freeing Obstack Objects
951 @subsection Freeing Objects in an Obstack
952 @cindex freeing (obstacks)
954 To free an object allocated in an obstack, use the function
955 @code{obstack_free}. Since the obstack is a stack of objects, freeing
956 one object automatically frees all other objects allocated more recently
961 @deftypefun void obstack_free (struct obstack *@var{obstack-ptr}, void *@var{object})
962 If @var{object} is a null pointer, everything allocated in the obstack
963 is freed. Otherwise, @var{object} must be the address of an object
964 allocated in the obstack. Then @var{object} is freed, along with
965 everything allocated in @var{obstack} since @var{object}.
968 Note that if @var{object} is a null pointer, the result is an
969 uninitialized obstack. To free all storage in an obstack but leave it
970 valid for further allocation, call @code{obstack_free} with the address
971 of the first object allocated on the obstack:
974 obstack_free (obstack_ptr, first_object_allocated_ptr);
977 Recall that the objects in an obstack are grouped into chunks. When all
978 the objects in a chunk become free, the obstack library automatically
979 frees the chunk (@pxref{Preparing for Obstacks}). Then other
980 obstacks, or non-obstack allocation, can reuse the space of the chunk.
982 @node Obstack Functions
983 @subsection Obstack Functions and Macros
986 The interfaces for using obstacks may be defined either as functions or
987 as macros, depending on the compiler. The obstack facility works with
988 all C compilers, including both ANSI C and traditional C, but there are
989 precautions you must take if you plan to use compilers other than GNU C.
991 If you are using an old-fashioned non-ANSI C compiler, all the obstack
992 ``functions'' are actually defined only as macros. You can call these
993 macros like functions, but you cannot use them in any other way (for
994 example, you cannot take their address).
996 Calling the macros requires a special precaution: namely, the first
997 operand (the obstack pointer) may not contain any side effects, because
998 it may be computed more than once. For example, if you write this:
1001 obstack_alloc (get_obstack (), 4);
1005 you will find that @code{get_obstack} may be called several times.
1006 If you use @code{*obstack_list_ptr++} as the obstack pointer argument,
1007 you will get very strange results since the incrementation may occur
1010 In ANSI C, each function has both a macro definition and a function
1011 definition. The function definition is used if you take the address of the
1012 function without calling it. An ordinary call uses the macro definition by
1013 default, but you can request the function definition instead by writing the
1014 function name in parentheses, as shown here:
1019 /* @r{Use the macro}. */
1020 x = (char *) obstack_alloc (obptr, size);
1021 /* @r{Call the function}. */
1022 x = (char *) (obstack_alloc) (obptr, size);
1023 /* @r{Take the address of the function}. */
1024 funcp = obstack_alloc;
1028 This is the same situation that exists in ANSI C for the standard library
1029 functions. @xref{Macro Definitions}.
1031 @strong{Warning:} When you do use the macros, you must observe the
1032 precaution of avoiding side effects in the first operand, even in ANSI
1035 If you use the GNU C compiler, this precaution is not necessary, because
1036 various language extensions in GNU C permit defining the macros so as to
1037 compute each argument only once.
1039 @node Growing Objects
1040 @subsection Growing Objects
1041 @cindex growing objects (in obstacks)
1042 @cindex changing the size of a block (obstacks)
1044 Because storage in obstack chunks is used sequentially, it is possible to
1045 build up an object step by step, adding one or more bytes at a time to the
1046 end of the object. With this technique, you do not need to know how much
1047 data you will put in the object until you come to the end of it. We call
1048 this the technique of @dfn{growing objects}. The special functions
1049 for adding data to the growing object are described in this section.
1051 You don't need to do anything special when you start to grow an object.
1052 Using one of the functions to add data to the object automatically
1053 starts it. However, it is necessary to say explicitly when the object is
1054 finished. This is done with the function @code{obstack_finish}.
1056 The actual address of the object thus built up is not known until the
1057 object is finished. Until then, it always remains possible that you will
1058 add so much data that the object must be copied into a new chunk.
1060 While the obstack is in use for a growing object, you cannot use it for
1061 ordinary allocation of another object. If you try to do so, the space
1062 already added to the growing object will become part of the other object.
1066 @deftypefun void obstack_blank (struct obstack *@var{obstack-ptr}, int @var{size})
1067 The most basic function for adding to a growing object is
1068 @code{obstack_blank}, which adds space without initializing it.
1073 @deftypefun void obstack_grow (struct obstack *@var{obstack-ptr}, void *@var{data}, int @var{size})
1074 To add a block of initialized space, use @code{obstack_grow}, which is
1075 the growing-object analogue of @code{obstack_copy}. It adds @var{size}
1076 bytes of data to the growing object, copying the contents from
1082 @deftypefun void obstack_grow0 (struct obstack *@var{obstack-ptr}, void *@var{data}, int @var{size})
1083 This is the growing-object analogue of @code{obstack_copy0}. It adds
1084 @var{size} bytes copied from @var{data}, followed by an additional null
1090 @deftypefun void obstack_1grow (struct obstack *@var{obstack-ptr}, char @var{c})
1091 To add one character at a time, use the function @code{obstack_1grow}.
1092 It adds a single byte containing @var{c} to the growing object.
1097 @deftypefun {void *} obstack_finish (struct obstack *@var{obstack-ptr})
1098 When you are finished growing the object, use the function
1099 @code{obstack_finish} to close it off and return its final address.
1101 Once you have finished the object, the obstack is available for ordinary
1102 allocation or for growing another object.
1104 This function can return a null pointer under the same conditions as
1105 @code{obstack_alloc} (@pxref{Allocation in an Obstack}).
1108 When you build an object by growing it, you will probably need to know
1109 afterward how long it became. You need not keep track of this as you grow
1110 the object, because you can find out the length from the obstack just
1111 before finishing the object with the function @code{obstack_object_size},
1112 declared as follows:
1116 @deftypefun int obstack_object_size (struct obstack *@var{obstack-ptr})
1117 This function returns the current size of the growing object, in bytes.
1118 Remember to call this function @emph{before} finishing the object.
1119 After it is finished, @code{obstack_object_size} will return zero.
1122 If you have started growing an object and wish to cancel it, you should
1123 finish it and then free it, like this:
1126 obstack_free (obstack_ptr, obstack_finish (obstack_ptr));
1130 This has no effect if no object was growing.
1132 @cindex shrinking objects
1133 You can use @code{obstack_blank} with a negative size argument to make
1134 the current object smaller. Just don't try to shrink it beyond zero
1135 length---there's no telling what will happen if you do that.
1137 @node Extra Fast Growing
1138 @subsection Extra Fast Growing Objects
1139 @cindex efficiency and obstacks
1141 The usual functions for growing objects incur overhead for checking
1142 whether there is room for the new growth in the current chunk. If you
1143 are frequently constructing objects in small steps of growth, this
1144 overhead can be significant.
1146 You can reduce the overhead by using special ``fast growth''
1147 functions that grow the object without checking. In order to have a
1148 robust program, you must do the checking yourself. If you do this checking
1149 in the simplest way each time you are about to add data to the object, you
1150 have not saved anything, because that is what the ordinary growth
1151 functions do. But if you can arrange to check less often, or check
1152 more efficiently, then you make the program faster.
1154 The function @code{obstack_room} returns the amount of room available
1155 in the current chunk. It is declared as follows:
1159 @deftypefun int obstack_room (struct obstack *@var{obstack-ptr})
1160 This returns the number of bytes that can be added safely to the current
1161 growing object (or to an object about to be started) in obstack
1162 @var{obstack} using the fast growth functions.
1165 While you know there is room, you can use these fast growth functions
1166 for adding data to a growing object:
1170 @deftypefun void obstack_1grow_fast (struct obstack *@var{obstack-ptr}, char @var{c})
1171 The function @code{obstack_1grow_fast} adds one byte containing the
1172 character @var{c} to the growing object in obstack @var{obstack-ptr}.
1177 @deftypefun void obstack_blank_fast (struct obstack *@var{obstack-ptr}, int @var{size})
1178 The function @code{obstack_blank_fast} adds @var{size} bytes to the
1179 growing object in obstack @var{obstack-ptr} without initializing them.
1182 When you check for space using @code{obstack_room} and there is not
1183 enough room for what you want to add, the fast growth functions
1184 are not safe. In this case, simply use the corresponding ordinary
1185 growth function instead. Very soon this will copy the object to a
1186 new chunk; then there will be lots of room available again.
1188 So, each time you use an ordinary growth function, check afterward for
1189 sufficient space using @code{obstack_room}. Once the object is copied
1190 to a new chunk, there will be plenty of space again, so the program will
1191 start using the fast growth functions again.
1198 add_string (struct obstack *obstack, char *ptr, int len)
1202 if (obstack_room (obstack) > len)
1204 /* @r{We have enough room: add everything fast.} */
1206 obstack_1grow_fast (obstack, *ptr++);
1210 /* @r{Not enough room. Add one character slowly,}
1211 @r{which may copy to a new chunk and make room.} */
1212 obstack_1grow (obstack, *ptr++);
1220 @node Status of an Obstack
1221 @subsection Status of an Obstack
1222 @cindex obstack status
1223 @cindex status of obstack
1225 Here are functions that provide information on the current status of
1226 allocation in an obstack. You can use them to learn about an object while
1231 @deftypefun {void *} obstack_base (struct obstack *@var{obstack-ptr})
1232 This function returns the tentative address of the beginning of the
1233 currently growing object in @var{obstack-ptr}. If you finish the object
1234 immediately, it will have that address. If you make it larger first, it
1235 may outgrow the current chunk---then its address will change!
1237 If no object is growing, this value says where the next object you
1238 allocate will start (once again assuming it fits in the current
1244 @deftypefun {void *} obstack_next_free (struct obstack *@var{obstack-ptr})
1245 This function returns the address of the first free byte in the current
1246 chunk of obstack @var{obstack-ptr}. This is the end of the currently
1247 growing object. If no object is growing, @code{obstack_next_free}
1248 returns the same value as @code{obstack_base}.
1253 @deftypefun int obstack_object_size (struct obstack *@var{obstack-ptr})
1254 This function returns the size in bytes of the currently growing object.
1255 This is equivalent to
1258 obstack_next_free (@var{obstack-ptr}) - obstack_base (@var{obstack-ptr})
1262 @node Obstacks Data Alignment
1263 @subsection Alignment of Data in Obstacks
1264 @cindex alignment (in obstacks)
1266 Each obstack has an @dfn{alignment boundary}; each object allocated in
1267 the obstack automatically starts on an address that is a multiple of the
1268 specified boundary. By default, this boundary is 4 bytes.
1270 To access an obstack's alignment boundary, use the macro
1271 @code{obstack_alignment_mask}, whose function prototype looks like
1276 @deftypefn Macro int obstack_alignment_mask (struct obstack *@var{obstack-ptr})
1277 The value is a bit mask; a bit that is 1 indicates that the corresponding
1278 bit in the address of an object should be 0. The mask value should be one
1279 less than a power of 2; the effect is that all object addresses are
1280 multiples of that power of 2. The default value of the mask is 3, so that
1281 addresses are multiples of 4. A mask value of 0 means an object can start
1282 on any multiple of 1 (that is, no alignment is required).
1284 The expansion of the macro @code{obstack_alignment_mask} is an lvalue,
1285 so you can alter the mask by assignment. For example, this statement:
1288 obstack_alignment_mask (obstack_ptr) = 0;
1292 has the effect of turning off alignment processing in the specified obstack.
1295 Note that a change in alignment mask does not take effect until
1296 @emph{after} the next time an object is allocated or finished in the
1297 obstack. If you are not growing an object, you can make the new
1298 alignment mask take effect immediately by calling @code{obstack_finish}.
1299 This will finish a zero-length object and then do proper alignment for
1302 @node Obstack Chunks
1303 @subsection Obstack Chunks
1304 @cindex efficiency of chunks
1307 Obstacks work by allocating space for themselves in large chunks, and
1308 then parceling out space in the chunks to satisfy your requests. Chunks
1309 are normally 4096 bytes long unless you specify a different chunk size.
1310 The chunk size includes 8 bytes of overhead that are not actually used
1311 for storing objects. Regardless of the specified size, longer chunks
1312 will be allocated when necessary for long objects.
1314 The obstack library allocates chunks by calling the function
1315 @code{obstack_chunk_alloc}, which you must define. When a chunk is no
1316 longer needed because you have freed all the objects in it, the obstack
1317 library frees the chunk by calling @code{obstack_chunk_free}, which you
1320 These two must be defined (as macros) or declared (as functions) in each
1321 source file that uses @code{obstack_init} (@pxref{Creating Obstacks}).
1322 Most often they are defined as macros like this:
1325 #define obstack_chunk_alloc xmalloc
1326 #define obstack_chunk_free free
1329 Note that these are simple macros (no arguments). Macro definitions with
1330 arguments will not work! It is necessary that @code{obstack_chunk_alloc}
1331 or @code{obstack_chunk_free}, alone, expand into a function name if it is
1332 not itself a function name.
1334 If you allocate chunks with @code{malloc}, the chunk size should be a
1335 power of 2. The default chunk size, 4096, was chosen because it is long
1336 enough to satisfy many typical requests on the obstack yet short enough
1337 not to waste too much memory in the portion of the last chunk not yet used.
1341 @deftypefn Macro int obstack_chunk_size (struct obstack *@var{obstack-ptr})
1342 This returns the chunk size of the given obstack.
1345 Since this macro expands to an lvalue, you can specify a new chunk size by
1346 assigning it a new value. Doing so does not affect the chunks already
1347 allocated, but will change the size of chunks allocated for that particular
1348 obstack in the future. It is unlikely to be useful to make the chunk size
1349 smaller, but making it larger might improve efficiency if you are
1350 allocating many objects whose size is comparable to the chunk size. Here
1351 is how to do so cleanly:
1354 if (obstack_chunk_size (obstack_ptr) < @var{new-chunk-size})
1355 obstack_chunk_size (obstack_ptr) = @var{new-chunk-size};
1358 @node Summary of Obstacks
1359 @subsection Summary of Obstack Functions
1361 Here is a summary of all the functions associated with obstacks. Each
1362 takes the address of an obstack (@code{struct obstack *}) as its first
1366 @item void obstack_init (struct obstack *@var{obstack-ptr})
1367 Initialize use of an obstack. @xref{Creating Obstacks}.
1369 @item void *obstack_alloc (struct obstack *@var{obstack-ptr}, int @var{size})
1370 Allocate an object of @var{size} uninitialized bytes.
1371 @xref{Allocation in an Obstack}.
1373 @item void *obstack_copy (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1374 Allocate an object of @var{size} bytes, with contents copied from
1375 @var{address}. @xref{Allocation in an Obstack}.
1377 @item void *obstack_copy0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1378 Allocate an object of @var{size}+1 bytes, with @var{size} of them copied
1379 from @var{address}, followed by a null character at the end.
1380 @xref{Allocation in an Obstack}.
1382 @item void obstack_free (struct obstack *@var{obstack-ptr}, void *@var{object})
1383 Free @var{object} (and everything allocated in the specified obstack
1384 more recently than @var{object}). @xref{Freeing Obstack Objects}.
1386 @item void obstack_blank (struct obstack *@var{obstack-ptr}, int @var{size})
1387 Add @var{size} uninitialized bytes to a growing object.
1388 @xref{Growing Objects}.
1390 @item void obstack_grow (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1391 Add @var{size} bytes, copied from @var{address}, to a growing object.
1392 @xref{Growing Objects}.
1394 @item void obstack_grow0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1395 Add @var{size} bytes, copied from @var{address}, to a growing object,
1396 and then add another byte containing a null character. @xref{Growing
1399 @item void obstack_1grow (struct obstack *@var{obstack-ptr}, char @var{data-char})
1400 Add one byte containing @var{data-char} to a growing object.
1401 @xref{Growing Objects}.
1403 @item void *obstack_finish (struct obstack *@var{obstack-ptr})
1404 Finalize the object that is growing and return its permanent address.
1405 @xref{Growing Objects}.
1407 @item int obstack_object_size (struct obstack *@var{obstack-ptr})
1408 Get the current size of the currently growing object. @xref{Growing
1411 @item void obstack_blank_fast (struct obstack *@var{obstack-ptr}, int @var{size})
1412 Add @var{size} uninitialized bytes to a growing object without checking
1413 that there is enough room. @xref{Extra Fast Growing}.
1415 @item void obstack_1grow_fast (struct obstack *@var{obstack-ptr}, char @var{data-char})
1416 Add one byte containing @var{data-char} to a growing object without
1417 checking that there is enough room. @xref{Extra Fast Growing}.
1419 @item int obstack_room (struct obstack *@var{obstack-ptr})
1420 Get the amount of room now available for growing the current object.
1421 @xref{Extra Fast Growing}.
1423 @item int obstack_alignment_mask (struct obstack *@var{obstack-ptr})
1424 The mask used for aligning the beginning of an object. This is an
1425 lvalue. @xref{Obstacks Data Alignment}.
1427 @item int obstack_chunk_size (struct obstack *@var{obstack-ptr})
1428 The size for allocating chunks. This is an lvalue. @xref{Obstack Chunks}.
1430 @item void *obstack_base (struct obstack *@var{obstack-ptr})
1431 Tentative starting address of the currently growing object.
1432 @xref{Status of an Obstack}.
1434 @item void *obstack_next_free (struct obstack *@var{obstack-ptr})
1435 Address just after the end of the currently growing object.
1436 @xref{Status of an Obstack}.
1439 @node Variable Size Automatic
1440 @section Automatic Storage with Variable Size
1441 @cindex automatic freeing
1442 @cindex @code{alloca} function
1443 @cindex automatic storage with variable size
1445 The function @code{alloca} supports a kind of half-dynamic allocation in
1446 which blocks are allocated dynamically but freed automatically.
1448 Allocating a block with @code{alloca} is an explicit action; you can
1449 allocate as many blocks as you wish, and compute the size at run time. But
1450 all the blocks are freed when you exit the function that @code{alloca} was
1451 called from, just as if they were automatic variables declared in that
1452 function. There is no way to free the space explicitly.
1454 The prototype for @code{alloca} is in @file{stdlib.h}. This function is
1460 @deftypefun {void *} alloca (size_t @var{size});
1461 The return value of @code{alloca} is the address of a block of @var{size}
1462 bytes of storage, allocated in the stack frame of the calling function.
1465 Do not use @code{alloca} inside the arguments of a function call---you
1466 will get unpredictable results, because the stack space for the
1467 @code{alloca} would appear on the stack in the middle of the space for
1468 the function arguments. An example of what to avoid is @code{foo (x,
1470 @c This might get fixed in future versions of GCC, but that won't make
1471 @c it safe with compilers generally.
1474 * Alloca Example:: Example of using @code{alloca}.
1475 * Advantages of Alloca:: Reasons to use @code{alloca}.
1476 * Disadvantages of Alloca:: Reasons to avoid @code{alloca}.
1477 * GNU C Variable-Size Arrays:: Only in GNU C, here is an alternative
1478 method of allocating dynamically and
1479 freeing automatically.
1482 @node Alloca Example
1483 @subsection @code{alloca} Example
1485 As an example of use of @code{alloca}, here is a function that opens a file
1486 name made from concatenating two argument strings, and returns a file
1487 descriptor or minus one signifying failure:
1491 open2 (char *str1, char *str2, int flags, int mode)
1493 char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
1494 strcpy (name, str1);
1495 strcat (name, str2);
1496 return open (name, flags, mode);
1501 Here is how you would get the same results with @code{malloc} and
1506 open2 (char *str1, char *str2, int flags, int mode)
1508 char *name = (char *) malloc (strlen (str1) + strlen (str2) + 1);
1511 fatal ("virtual memory exceeded");
1512 strcpy (name, str1);
1513 strcat (name, str2);
1514 desc = open (name, flags, mode);
1520 As you can see, it is simpler with @code{alloca}. But @code{alloca} has
1521 other, more important advantages, and some disadvantages.
1523 @node Advantages of Alloca
1524 @subsection Advantages of @code{alloca}
1526 Here are the reasons why @code{alloca} may be preferable to @code{malloc}:
1530 Using @code{alloca} wastes very little space and is very fast. (It is
1531 open-coded by the GNU C compiler.)
1534 Since @code{alloca} does not have separate pools for different sizes of
1535 block, space used for any size block can be reused for any other size.
1536 @code{alloca} does not cause storage fragmentation.
1540 Nonlocal exits done with @code{longjmp} (@pxref{Non-Local Exits})
1541 automatically free the space allocated with @code{alloca} when they exit
1542 through the function that called @code{alloca}. This is the most
1543 important reason to use @code{alloca}.
1545 To illustrate this, suppose you have a function
1546 @code{open_or_report_error} which returns a descriptor, like
1547 @code{open}, if it succeeds, but does not return to its caller if it
1548 fails. If the file cannot be opened, it prints an error message and
1549 jumps out to the command level of your program using @code{longjmp}.
1550 Let's change @code{open2} (@pxref{Alloca Example}) to use this
1555 open2 (char *str1, char *str2, int flags, int mode)
1557 char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
1558 strcpy (name, str1);
1559 strcat (name, str2);
1560 return open_or_report_error (name, flags, mode);
1565 Because of the way @code{alloca} works, the storage it allocates is
1566 freed even when an error occurs, with no special effort required.
1568 By contrast, the previous definition of @code{open2} (which uses
1569 @code{malloc} and @code{free}) would develop a storage leak if it were
1570 changed in this way. Even if you are willing to make more changes to
1571 fix it, there is no easy way to do so.
1574 @node Disadvantages of Alloca
1575 @subsection Disadvantages of @code{alloca}
1577 @cindex @code{alloca} disadvantages
1578 @cindex disadvantages of @code{alloca}
1579 These are the disadvantages of @code{alloca} in comparison with
1584 If you try to allocate more storage than the machine can provide, you
1585 don't get a clean error message. Instead you get a fatal signal like
1586 the one you would get from an infinite recursion; probably a
1587 segmentation violation (@pxref{Program Error Signals}).
1590 Some non-GNU systems fail to support @code{alloca}, so it is less
1591 portable. However, a slower emulation of @code{alloca} written in C
1592 is available for use on systems with this deficiency.
1595 @node GNU C Variable-Size Arrays
1596 @subsection GNU C Variable-Size Arrays
1597 @cindex variable-sized arrays
1599 In GNU C, you can replace most uses of @code{alloca} with an array of
1600 variable size. Here is how @code{open2} would look then:
1603 int open2 (char *str1, char *str2, int flags, int mode)
1605 char name[strlen (str1) + strlen (str2) + 1];
1606 strcpy (name, str1);
1607 strcat (name, str2);
1608 return open (name, flags, mode);
1612 But @code{alloca} is not always equivalent to a variable-sized array, for
1617 A variable size array's space is freed at the end of the scope of the
1618 name of the array. The space allocated with @code{alloca}
1619 remains until the end of the function.
1622 It is possible to use @code{alloca} within a loop, allocating an
1623 additional block on each iteration. This is impossible with
1624 variable-sized arrays.
1627 @strong{Note:} If you mix use of @code{alloca} and variable-sized arrays
1628 within one function, exiting a scope in which a variable-sized array was
1629 declared frees all blocks allocated with @code{alloca} during the
1630 execution of that scope.
1633 @node Relocating Allocator
1634 @section Relocating Allocator
1636 @cindex relocating memory allocator
1637 Any system of dynamic memory allocation has overhead: the amount of
1638 space it uses is more than the amount the program asks for. The
1639 @dfn{relocating memory allocator} achieves very low overhead by moving
1640 blocks in memory as necessary, on its own initiative.
1643 * Relocator Concepts:: How to understand relocating allocation.
1644 * Using Relocator:: Functions for relocating allocation.
1647 @node Relocator Concepts
1648 @subsection Concepts of Relocating Allocation
1651 The @dfn{relocating memory allocator} achieves very low overhead by
1652 moving blocks in memory as necessary, on its own initiative.
1655 When you allocate a block with @code{malloc}, the address of the block
1656 never changes unless you use @code{realloc} to change its size. Thus,
1657 you can safely store the address in various places, temporarily or
1658 permanently, as you like. This is not safe when you use the relocating
1659 memory allocator, because any and all relocatable blocks can move
1660 whenever you allocate memory in any fashion. Even calling @code{malloc}
1661 or @code{realloc} can move the relocatable blocks.
1664 For each relocatable block, you must make a @dfn{handle}---a pointer
1665 object in memory, designated to store the address of that block. The
1666 relocating allocator knows where each block's handle is, and updates the
1667 address stored there whenever it moves the block, so that the handle
1668 always points to the block. Each time you access the contents of the
1669 block, you should fetch its address anew from the handle.
1671 To call any of the relocating allocator functions from a signal handler
1672 is almost certainly incorrect, because the signal could happen at any
1673 time and relocate all the blocks. The only way to make this safe is to
1674 block the signal around any access to the contents of any relocatable
1675 block---not a convenient mode of operation. @xref{Nonreentrancy}.
1677 @node Using Relocator
1678 @subsection Allocating and Freeing Relocatable Blocks
1681 In the descriptions below, @var{handleptr} designates the address of the
1682 handle. All the functions are declared in @file{malloc.h}; all are GNU
1687 @deftypefun {void *} r_alloc (void **@var{handleptr}, size_t @var{size})
1688 This function allocates a relocatable block of size @var{size}. It
1689 stores the block's address in @code{*@var{handleptr}} and returns
1690 a non-null pointer to indicate success.
1692 If @code{r_alloc} can't get the space needed, it stores a null pointer
1693 in @code{*@var{handleptr}}, and returns a null pointer.
1698 @deftypefun void r_alloc_free (void **@var{handleptr})
1699 This function is the way to free a relocatable block. It frees the
1700 block that @code{*@var{handleptr}} points to, and stores a null pointer
1701 in @code{*@var{handleptr}} to show it doesn't point to an allocated
1707 @deftypefun {void *} r_re_alloc (void **@var{handleptr}, size_t @var{size})
1708 The function @code{r_re_alloc} adjusts the size of the block that
1709 @code{*@var{handleptr}} points to, making it @var{size} bytes long. It
1710 stores the address of the resized block in @code{*@var{handleptr}} and
1711 returns a non-null pointer to indicate success.
1713 If enough memory is not available, this function returns a null pointer
1714 and does not modify @code{*@var{handleptr}}.
1717 @node Memory Warnings
1718 @section Memory Usage Warnings
1719 @cindex memory usage warnings
1720 @cindex warnings of memory almost full
1723 You can ask for warnings as the program approaches running out of memory
1724 space, by calling @code{memory_warnings}. This tells @code{malloc} to
1725 check memory usage every time it asks for more memory from the operating
1726 system. This is a GNU extension declared in @file{malloc.h}.
1730 @deftypefun void memory_warnings (void *@var{start}, void (*@var{warn-func}) (const char *))
1731 Call this function to request warnings for nearing exhaustion of virtual
1734 The argument @var{start} says where data space begins, in memory. The
1735 allocator compares this against the last address used and against the
1736 limit of data space, to determine the fraction of available memory in
1737 use. If you supply zero for @var{start}, then a default value is used
1738 which is right in most circumstances.
1740 For @var{warn-func}, supply a function that @code{malloc} can call to
1741 warn you. It is called with a string (a warning message) as argument.
1742 Normally it ought to display the string for the user to read.
1745 The warnings come when memory becomes 75% full, when it becomes 85%
1746 full, and when it becomes 95% full. Above 95% you get another warning
1747 each time memory usage increases.