]> git.ipfire.org Git - thirdparty/glibc.git/blame - manual/memory.texi
(PENTIUM:CPunix:4.0*:*): New case.
[thirdparty/glibc.git] / manual / memory.texi
CommitLineData
28f540f4
RM
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
9The GNU system provides several methods for allocating memory space
10under explicit program control. They vary in generality and in
11efficiency.
12
13@iftex
14@itemize @bullet
15@item
16The @code{malloc} facility allows fully general dynamic allocation.
17@xref{Unconstrained Allocation}.
18
19@item
20Obstacks are another facility, less general than @code{malloc} but more
21efficient and convenient for stacklike allocation. @xref{Obstacks}.
22
23@item
24The function @code{alloca} lets you allocate storage dynamically that
25will 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* 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.
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
51determine as they are running where to store some information. You need
52dynamic allocation when the number of memory blocks you need, or how
53long you continue to need them, depends on the data you are working on.
54
55For example, you may need a block to store a line read from an input file;
56since there is no limit to how long a line can be, you must allocate the
57storage dynamically and make it dynamically larger as you read more of the
58line.
59
60Or, you may need a block for each record or each definition in the input
61data; since you can't know in advance how many there will be, you must
62allocate a new block for each record or definition as you read it.
63
64When you use dynamic allocation, the allocation of a block of memory is an
65action that the program requests explicitly. You call a function or macro
66when you want to allocate space, and specify the size with an argument. If
67you want to free the space, you do so by calling another function or macro.
68You 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
73The C language supports two kinds of memory allocation through the variables
74in C programs:
75
76@itemize @bullet
77@item
78@dfn{Static allocation} is what happens when you declare a static or
79global variable. Each static or global variable defines one block of
80space, of a fixed size. The space is allocated once, when your program
81is started, and is never freed.
82
83@item
84@dfn{Automatic allocation} happens when you declare an automatic
85variable, such as a function argument or a local variable. The space
86for an automatic variable is allocated when the compound statement
87containing the declaration is entered, and is freed when that
88compound statement is exited.
89
90In GNU C, the length of the automatic storage can be an expression
91that varies. In other C implementations, it must be a constant.
92@end itemize
93
94Dynamic allocation is not supported by C variables; there is no storage
95class ``dynamic'', and there can never be a C variable whose value is
96stored in dynamically allocated space. The only way to refer to
97dynamically allocated space is through a pointer. Because it is less
98convenient, and because the actual process of dynamic allocation
99requires more computation time, programmers generally use dynamic
100allocation only when neither static nor automatic allocation will serve.
101
102For 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
104foobar} whose contents are the dynamically allocated space. But you can
105declare a variable of pointer type @code{struct foobar *} and assign it the
106address 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
125The most general dynamic allocation facility is @code{malloc}. It
126allows you to allocate blocks of memory of any size at any time, make
127them bigger or smaller at any time, and free the blocks individually at
128any 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* 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.
149@end menu
150
151@node Basic Allocation
152@subsection Basic Storage Allocation
153@cindex allocation of memory with @code{malloc}
154
155To allocate a block of memory, call @code{malloc}. The prototype for
156this function is in @file{stdlib.h}.
157@pindex stdlib.h
158
159@comment malloc.h stdlib.h
160@comment ANSI
161@deftypefun {void *} malloc (size_t @var{size})
162This function returns a pointer to a newly allocated block @var{size}
163bytes long, or a null pointer if the block could not be allocated.
164@end deftypefun
165
166The contents of the block are undefined; you must initialize it yourself
167(or use @code{calloc} instead; @pxref{Allocating Cleared Space}).
168Normally you would cast the value as a pointer to the kind of object
169that you want to store in the block. Here we show an example of doing
170so, and of initializing the space with zeros using the library function
171@code{memset} (@pxref{Copying and Concatenation}):
172
173@smallexample
174struct foo *ptr;
175@dots{}
176ptr = (struct foo *) malloc (sizeof (struct foo));
177if (ptr == 0) abort ();
178memset (ptr, 0, sizeof (struct foo));
179@end smallexample
180
181You can store the result of @code{malloc} into any pointer variable
182without a cast, because ANSI C automatically converts the type
183@code{void *} to another type of pointer when necessary. But the cast
184is necessary in contexts other than assignment operators or if you might
185want your code to run in traditional C.
186
187Remember that when allocating space for a string, the argument to
188@code{malloc} must be one plus the length of the string. This is
189because a string is terminated with a null character that doesn't count
190in the ``length'' of the string but does need space. For example:
191
192@smallexample
193char *ptr;
194@dots{}
195ptr = (char *) malloc (length + 1);
196@end smallexample
197
198@noindent
199@xref{Representation of Strings}, for more information about this.
200
201@node Malloc Examples
202@subsection Examples of @code{malloc}
203
204If no more space is available, @code{malloc} returns a null pointer.
205You should check the value of @emph{every} call to @code{malloc}. It is
206useful to write a subroutine that calls @code{malloc} and reports an
207error if the value is a null pointer, returning only if the value is
208nonzero. This function is conventionally called @code{xmalloc}. Here
209it is:
210
211@smallexample
212void *
213xmalloc (size_t size)
214@{
215 register void *value = malloc (size);
216 if (value == 0)
217 fatal ("virtual memory exhausted");
218 return value;
219@}
220@end smallexample
221
222Here is a real example of using @code{malloc} (by way of @code{xmalloc}).
223The function @code{savestring} will copy a sequence of characters into
224a newly allocated null-terminated string:
225
226@smallexample
227@group
228char *
229savestring (const char *ptr, size_t len)
230@{
231 register char *value = (char *) xmalloc (len + 1);
232 memcpy (value, ptr, len);
233 value[len] = '\0';
234 return value;
235@}
236@end group
237@end smallexample
238
239The block that @code{malloc} gives you is guaranteed to be aligned so
240that it can hold any type of data. In the GNU system, the address is
241always a multiple of eight; if the size of block is 16 or more, then the
242address is always a multiple of 16. Only rarely is any higher boundary
243(such as a page boundary) necessary; for those cases, use
244@code{memalign} or @code{valloc} (@pxref{Aligned Memory Blocks}).
245
246Note that the memory located after the end of the block is likely to be
247in use for something else; perhaps a block already allocated by another
248call to @code{malloc}. If you attempt to treat the block as longer than
249you asked for it to be, you are liable to destroy the data that
250@code{malloc} uses to keep track of its blocks, or you may destroy the
251contents of another block. If you have already allocated a block and
252discover you want it to be bigger, use @code{realloc} (@pxref{Changing
253Block Size}).
254
255@node Freeing after Malloc
256@subsection Freeing Memory Allocated with @code{malloc}
257@cindex freeing memory allocated with @code{malloc}
258@cindex heap, freeing memory from
259
260When you no longer need a block that you got with @code{malloc}, use the
261function @code{free} to make the block available to be allocated again.
262The prototype for this function is in @file{stdlib.h}.
263@pindex stdlib.h
264
265@comment malloc.h stdlib.h
266@comment ANSI
267@deftypefun void free (void *@var{ptr})
268The @code{free} function deallocates the block of storage pointed at
269by @var{ptr}.
270@end deftypefun
271
272@comment stdlib.h
273@comment Sun
274@deftypefun void cfree (void *@var{ptr})
275This function does the same thing as @code{free}. It's provided for
276backward compatibility with SunOS; you should use @code{free} instead.
277@end deftypefun
278
279Freeing a block alters the contents of the block. @strong{Do not expect to
280find any data (such as a pointer to the next block in a chain of blocks) in
281the block after freeing it.} Copy whatever you need out of the block before
282freeing it! Here is an example of the proper way to free all the blocks in
283a chain, and the strings that they point to:
284
285@smallexample
286struct chain
287 @{
288 struct chain *next;
289 char *name;
290 @}
291
292void
293free_chain (struct chain *chain)
294@{
295 while (chain != 0)
296 @{
297 struct chain *next = chain->next;
298 free (chain->name);
299 free (chain);
300 chain = next;
301 @}
302@}
303@end smallexample
304
305Occasionally, @code{free} can actually return memory to the operating
306system and make the process smaller. Usually, all it can do is allow a
307later call to @code{malloc} to reuse the space. In the meantime, the
308space remains in your program as part of a free-list used internally by
309@code{malloc}.
310
311There is no point in freeing blocks at the end of a program, because all
312of the program's space is given back to the system when the process
313terminates.
314
315@node Changing Block Size
316@subsection Changing the Size of a Block
317@cindex changing the size of a block (@code{malloc})
318
319Often you do not know for certain how big a block you will ultimately need
320at the time you must begin to use the block. For example, the block might
321be a buffer that you use to hold a line being read from a file; no matter
322how long you make the buffer initially, you may encounter a line that is
323longer.
324
325You can make the block longer by calling @code{realloc}. This function
326is declared in @file{stdlib.h}.
327@pindex stdlib.h
328
329@comment malloc.h stdlib.h
330@comment ANSI
331@deftypefun {void *} realloc (void *@var{ptr}, size_t @var{newsize})
332The @code{realloc} function changes the size of the block whose address is
333@var{ptr} to be @var{newsize}.
334
335Since the space after the end of the block may be in use, @code{realloc}
336may find it necessary to copy the block to a new address where more free
337space is available. The value of @code{realloc} is the new address of the
338block. If the block needs to be moved, @code{realloc} copies the old
339contents.
340
341If you pass a null pointer for @var{ptr}, @code{realloc} behaves just
342like @samp{malloc (@var{newsize})}. This can be convenient, but beware
343that older implementations (before ANSI C) may not support this
344behavior, and will probably crash when @code{realloc} is passed a null
345pointer.
346@end deftypefun
347
348Like @code{malloc}, @code{realloc} may return a null pointer if no
349memory space is available to make the block bigger. When this happens,
350the original block is untouched; it has not been modified or relocated.
351
352In most cases it makes no difference what happens to the original block
353when @code{realloc} fails, because the application program cannot continue
354when it is out of memory, and the only thing to do is to give a fatal error
355message. Often it is convenient to write and use a subroutine,
356conventionally called @code{xrealloc}, that takes care of the error message
357as @code{xmalloc} does for @code{malloc}:
358
359@smallexample
360void *
361xrealloc (void *ptr, size_t size)
362@{
363 register void *value = realloc (ptr, size);
364 if (value == 0)
365 fatal ("Virtual memory exhausted");
366 return value;
367@}
368@end smallexample
369
370You can also use @code{realloc} to make a block smaller. The reason you
371would do this is to avoid tying up a lot of memory space when only a little
372is needed. Making a block smaller sometimes necessitates copying it, so it
373can fail if no other space is available.
374
375If the new size you specify is the same as the old size, @code{realloc}
376is guaranteed to change nothing and return the same address that you gave.
377
378@node Allocating Cleared Space
379@subsection Allocating Cleared Space
380
381The function @code{calloc} allocates memory and clears it to zero. It
382is declared in @file{stdlib.h}.
383@pindex stdlib.h
384
385@comment malloc.h stdlib.h
386@comment ANSI
387@deftypefun {void *} calloc (size_t @var{count}, size_t @var{eltsize})
388This function allocates a block long enough to contain a vector of
389@var{count} elements, each of size @var{eltsize}. Its contents are
390cleared to zero before @code{calloc} returns.
391@end deftypefun
392
393You could define @code{calloc} as follows:
394
395@smallexample
396void *
397calloc (size_t count, size_t eltsize)
398@{
399 size_t size = count * eltsize;
400 void *value = malloc (size);
401 if (value != 0)
402 memset (value, 0, size);
403 return value;
404@}
405@end smallexample
406
407@node Efficiency and Malloc
408@subsection Efficiency Considerations for @code{malloc}
409@cindex efficiency and @code{malloc}
410
411To make the best use of @code{malloc}, it helps to know that the GNU
412version of @code{malloc} always dispenses small amounts of memory in
413blocks whose sizes are powers of two. It keeps separate pools for each
414power of two. This holds for sizes up to a page size. Therefore, if
415you are free to choose the size of a small block in order to make
416@code{malloc} more efficient, make it a power of two.
417@c !!! xref getpagesize
418
419Once a page is split up for a particular block size, it can't be reused
420for another size unless all the blocks in it are freed. In many
421programs, this is unlikely to happen. Thus, you can sometimes make a
422program use memory more efficiently by using blocks of the same size for
423many different purposes.
424
425When you ask for memory blocks of a page or larger, @code{malloc} uses a
426different strategy; it rounds the size up to a multiple of a page, and
427it can coalesce and split blocks as needed.
428
429The reason for the two strategies is that it is important to allocate
430and free small blocks as fast as possible, but speed is less important
431for a large block since the program normally spends a fair amount of
432time using it. Also, large blocks are normally fewer in number.
433Therefore, for large blocks, it makes sense to use a method which takes
434more time to minimize the wasted space.
435
436@node Aligned Memory Blocks
437@subsection Allocating Aligned Memory Blocks
438
439@cindex page boundary
440@cindex alignment (with @code{malloc})
441@pindex stdlib.h
442The address of a block returned by @code{malloc} or @code{realloc} in
443the GNU system is always a multiple of eight. If you need a block whose
444address is a multiple of a higher power of two than that, use
445@code{memalign} or @code{valloc}. These functions are declared in
446@file{stdlib.h}.
447
448With the GNU library, you can use @code{free} to free the blocks that
449@code{memalign} and @code{valloc} return. That does not work in BSD,
450however---BSD does not provide any way to free such blocks.
451
452@comment malloc.h stdlib.h
453@comment BSD
22a1292a 454@deftypefun {void *} memalign (size_t @var{boundary}, size_t @var{size})
28f540f4
RM
455The @code{memalign} function allocates a block of @var{size} bytes whose
456address is a multiple of @var{boundary}. The @var{boundary} must be a
457power of two! The function @code{memalign} works by calling
458@code{malloc} to allocate a somewhat larger block, and then returning an
459address within the block that is on the specified boundary.
460@end deftypefun
461
462@comment malloc.h stdlib.h
463@comment BSD
464@deftypefun {void *} valloc (size_t @var{size})
465Using @code{valloc} is like using @code{memalign} and passing the page size
466as the value of the second argument. It is implemented like this:
467
468@smallexample
469void *
470valloc (size_t size)
471@{
22a1292a 472 return memalign (getpagesize (), size);
28f540f4
RM
473@}
474@end smallexample
475@c !!! xref getpagesize
476@end deftypefun
477
478@node Heap Consistency Checking
479@subsection Heap Consistency Checking
480
481@cindex heap consistency checking
482@cindex consistency checking, of heap
483
484You can ask @code{malloc} to check the consistency of dynamic storage by
485using the @code{mcheck} function. This function is a GNU extension,
486declared in @file{malloc.h}.
487@pindex malloc.h
488
489@comment malloc.h
490@comment GNU
491@deftypefun int mcheck (void (*@var{abortfn}) (enum mcheck_status @var{status}))
492Calling @code{mcheck} tells @code{malloc} to perform occasional
493consistency checks. These will catch things such as writing
494past the end of a block that was allocated with @code{malloc}.
495
496The @var{abortfn} argument is the function to call when an inconsistency
497is found. If you supply a null pointer, then @code{mcheck} uses a
498default function which prints a message and calls @code{abort}
499(@pxref{Aborting a Program}). The function you supply is called with
500one argument, which says what sort of inconsistency was detected; its
501type is described below.
502
503It is too late to begin allocation checking once you have allocated
504anything with @code{malloc}. So @code{mcheck} does nothing in that
505case. The function returns @code{-1} if you call it too late, and
506@code{0} otherwise (when it is successful).
507
508The easiest way to arrange to call @code{mcheck} early enough is to use
509the option @samp{-lmcheck} when you link your program; then you don't
510need to modify your program source at all.
511@end deftypefun
512
513@deftypefun {enum mcheck_status} mprobe (void *@var{pointer})
514The @code{mprobe} function lets you explicitly check for inconsistencies
515in a particular allocated block. You must have already called
516@code{mcheck} at the beginning of the program, to do its occasional
517checks; calling @code{mprobe} requests an additional consistency check
518to be done at the time of the call.
519
520The argument @var{pointer} must be a pointer returned by @code{malloc}
521or @code{realloc}. @code{mprobe} returns a value that says what
522inconsistency, if any, was found. The values are described below.
523@end deftypefun
524
525@deftp {Data Type} {enum mcheck_status}
526This enumerated type describes what kind of inconsistency was detected
527in an allocated block, if any. Here are the possible values:
528
529@table @code
530@item MCHECK_DISABLED
531@code{mcheck} was not called before the first allocation.
532No consistency checking can be done.
533@item MCHECK_OK
534No inconsistency detected.
535@item MCHECK_HEAD
536The data immediately before the block was modified.
537This commonly happens when an array index or pointer
538is decremented too far.
539@item MCHECK_TAIL
540The data immediately after the block was modified.
541This commonly happens when an array index or pointer
542is incremented too far.
543@item MCHECK_FREE
544The block was already freed.
545@end table
546@end deftp
547
548@node Hooks for Malloc
549@subsection Storage Allocation Hooks
550@cindex allocation hooks, for @code{malloc}
551
552The GNU C library lets you modify the behavior of @code{malloc},
553@code{realloc}, and @code{free} by specifying appropriate hook
554functions. You can use these hooks to help you debug programs that use
555dynamic storage allocation, for example.
556
557The hook variables are declared in @file{malloc.h}.
558@pindex malloc.h
559
560@comment malloc.h
561@comment GNU
562@defvar __malloc_hook
563The value of this variable is a pointer to function that @code{malloc}
564uses whenever it is called. You should define this function to look
565like @code{malloc}; that is, like:
566
567@smallexample
568void *@var{function} (size_t @var{size})
569@end smallexample
570@end defvar
571
572@comment malloc.h
573@comment GNU
574@defvar __realloc_hook
575The value of this variable is a pointer to function that @code{realloc}
576uses whenever it is called. You should define this function to look
577like @code{realloc}; that is, like:
578
579@smallexample
580void *@var{function} (void *@var{ptr}, size_t @var{size})
581@end smallexample
582@end defvar
583
584@comment malloc.h
585@comment GNU
586@defvar __free_hook
587The value of this variable is a pointer to function that @code{free}
588uses whenever it is called. You should define this function to look
589like @code{free}; that is, like:
590
591@smallexample
592void @var{function} (void *@var{ptr})
593@end smallexample
594@end defvar
595
596You must make sure that the function you install as a hook for one of
597these functions does not call that function recursively without restoring
598the old value of the hook first! Otherwise, your program will get stuck
599in an infinite recursion.
600
601Here is an example showing how to use @code{__malloc_hook} properly. It
602installs a function that prints out information every time @code{malloc}
603is called.
604
605@smallexample
606static void *(*old_malloc_hook) (size_t);
607static void *
608my_malloc_hook (size_t size)
609@{
610 void *result;
611 __malloc_hook = old_malloc_hook;
612 result = malloc (size);
613 /* @r{@code{printf} might call @code{malloc}, so protect it too.} */
614 printf ("malloc (%u) returns %p\n", (unsigned int) size, result);
615 __malloc_hook = my_malloc_hook;
616 return result;
617@}
618
619main ()
620@{
621 ...
622 old_malloc_hook = __malloc_hook;
623 __malloc_hook = my_malloc_hook;
624 ...
625@}
626@end smallexample
627
628The @code{mcheck} function (@pxref{Heap Consistency Checking}) works by
629installing such hooks.
630
631@c __morecore, __after_morecore_hook are undocumented
632@c It's not clear whether to document them.
633
634@node Statistics of Malloc
635@subsection Statistics for Storage Allocation with @code{malloc}
636
637@cindex allocation statistics
638You can get information about dynamic storage allocation by calling the
639@code{mstats} function. This function and its associated data type are
640declared in @file{malloc.h}; they are a GNU extension.
641@pindex malloc.h
642
643@comment malloc.h
644@comment GNU
645@deftp {Data Type} {struct mstats}
646This structure type is used to return information about the dynamic
647storage allocator. It contains the following members:
648
649@table @code
650@item size_t bytes_total
651This is the total size of memory managed by @code{malloc}, in bytes.
652
653@item size_t chunks_used
654This is the number of chunks in use. (The storage allocator internally
655gets chunks of memory from the operating system, and then carves them up
656to satisfy individual @code{malloc} requests; see @ref{Efficiency and
657Malloc}.)
658
659@item size_t bytes_used
660This is the number of bytes in use.
661
662@item size_t chunks_free
663This is the number of chunks which are free -- that is, that have been
664allocated by the operating system to your program, but which are not
665now being used.
666
667@item size_t bytes_free
668This is the number of bytes which are free.
669@end table
670@end deftp
671
672@comment malloc.h
673@comment GNU
674@deftypefun {struct mstats} mstats (void)
675This function returns information about the current dynamic memory usage
676in a structure of type @code{struct mstats}.
677@end deftypefun
678
679@node Summary of Malloc
680@subsection Summary of @code{malloc}-Related Functions
681
682Here is a summary of the functions that work with @code{malloc}:
683
684@table @code
685@item void *malloc (size_t @var{size})
686Allocate a block of @var{size} bytes. @xref{Basic Allocation}.
687
688@item void free (void *@var{addr})
689Free a block previously allocated by @code{malloc}. @xref{Freeing after
690Malloc}.
691
692@item void *realloc (void *@var{addr}, size_t @var{size})
693Make a block previously allocated by @code{malloc} larger or smaller,
694possibly by copying it to a new location. @xref{Changing Block Size}.
695
696@item void *calloc (size_t @var{count}, size_t @var{eltsize})
697Allocate a block of @var{count} * @var{eltsize} bytes using
698@code{malloc}, and set its contents to zero. @xref{Allocating Cleared
699Space}.
700
701@item void *valloc (size_t @var{size})
702Allocate a block of @var{size} bytes, starting on a page boundary.
703@xref{Aligned Memory Blocks}.
704
705@item void *memalign (size_t @var{size}, size_t @var{boundary})
706Allocate a block of @var{size} bytes, starting on an address that is a
707multiple of @var{boundary}. @xref{Aligned Memory Blocks}.
708
709@item int mcheck (void (*@var{abortfn}) (void))
710Tell @code{malloc} to perform occasional consistency checks on
711dynamically allocated memory, and to call @var{abortfn} when an
712inconsistency is found. @xref{Heap Consistency Checking}.
713
714@item void *(*__malloc_hook) (size_t @var{size})
715A pointer to a function that @code{malloc} uses whenever it is called.
716
717@item void *(*__realloc_hook) (void *@var{ptr}, size_t @var{size})
718A pointer to a function that @code{realloc} uses whenever it is called.
719
720@item void (*__free_hook) (void *@var{ptr})
721A pointer to a function that @code{free} uses whenever it is called.
722
723@item struct mstats mstats (void)
724Return information about the current dynamic memory usage.
725@xref{Statistics of Malloc}.
726@end table
727
728@node Obstacks
729@section Obstacks
730@cindex obstacks
731
732An @dfn{obstack} is a pool of memory containing a stack of objects. You
733can create any number of separate obstacks, and then allocate objects in
734specified obstacks. Within each obstack, the last object allocated must
735always be the first one freed, but distinct obstacks are independent of
736each other.
737
738Aside from this one constraint of order of freeing, obstacks are totally
739general: an obstack can contain any number of objects of any size. They
740are implemented with macros, so allocation is usually very fast as long as
741the objects are usually small. And the only space overhead per object is
742the padding needed to start each object on a suitable boundary.
743
744@menu
745* Creating Obstacks:: How to declare an obstack in your program.
746* Preparing for Obstacks:: Preparations needed before you can
747 use obstacks.
748* Allocation in an Obstack:: Allocating objects in an obstack.
749* Freeing Obstack Objects:: Freeing objects in an obstack.
750* Obstack Functions:: The obstack functions are both
751 functions and macros.
752* Growing Objects:: Making an object bigger by stages.
753* Extra Fast Growing:: Extra-high-efficiency (though more
754 complicated) growing objects.
755* Status of an Obstack:: Inquiries about the status of an obstack.
756* Obstacks Data Alignment:: Controlling alignment of objects in obstacks.
757* Obstack Chunks:: How obstacks obtain and release chunks;
758 efficiency considerations.
a5113b14 759* Summary of Obstacks::
28f540f4
RM
760@end menu
761
762@node Creating Obstacks
763@subsection Creating Obstacks
764
765The utilities for manipulating obstacks are declared in the header
766file @file{obstack.h}.
767@pindex obstack.h
768
769@comment obstack.h
770@comment GNU
771@deftp {Data Type} {struct obstack}
772An obstack is represented by a data structure of type @code{struct
773obstack}. This structure has a small fixed size; it records the status
774of the obstack and how to find the space in which objects are allocated.
775It does not contain any of the objects themselves. You should not try
776to access the contents of the structure directly; use only the functions
777described in this chapter.
778@end deftp
779
780You can declare variables of type @code{struct obstack} and use them as
781obstacks, or you can allocate obstacks dynamically like any other kind
782of object. Dynamic allocation of obstacks allows your program to have a
783variable number of different stacks. (You can even allocate an
784obstack structure in another obstack, but this is rarely useful.)
785
786All the functions that work with obstacks require you to specify which
787obstack to use. You do this with a pointer of type @code{struct obstack
788*}. In the following, we often say ``an obstack'' when strictly
789speaking the object at hand is such a pointer.
790
791The objects in the obstack are packed into large blocks called
792@dfn{chunks}. The @code{struct obstack} structure points to a chain of
793the chunks currently in use.
794
795The obstack library obtains a new chunk whenever you allocate an object
796that won't fit in the previous chunk. Since the obstack library manages
797chunks automatically, you don't need to pay much attention to them, but
798you do need to supply a function which the obstack library should use to
799get a chunk. Usually you supply a function which uses @code{malloc}
800directly or indirectly. You must also supply a function to free a chunk.
801These matters are described in the following section.
802
803@node Preparing for Obstacks
804@subsection Preparing for Using Obstacks
805
806Each source file in which you plan to use the obstack functions
807must include the header file @file{obstack.h}, like this:
808
809@smallexample
810#include <obstack.h>
811@end smallexample
812
813@findex obstack_chunk_alloc
814@findex obstack_chunk_free
815Also, if the source file uses the macro @code{obstack_init}, it must
816declare or define two functions or macros that will be called by the
817obstack library. One, @code{obstack_chunk_alloc}, is used to allocate
818the chunks of memory into which objects are packed. The other,
819@code{obstack_chunk_free}, is used to return chunks when the objects in
820them are freed. These macros should appear before any use of obstacks
821in the source file.
822
823Usually these are defined to use @code{malloc} via the intermediary
824@code{xmalloc} (@pxref{Unconstrained Allocation}). This is done with
825the following pair of macro definitions:
826
827@smallexample
828#define obstack_chunk_alloc xmalloc
829#define obstack_chunk_free free
830@end smallexample
831
832@noindent
833Though the storage you get using obstacks really comes from @code{malloc},
834using obstacks is faster because @code{malloc} is called less often, for
835larger blocks of memory. @xref{Obstack Chunks}, for full details.
836
837At run time, before the program can use a @code{struct obstack} object
838as an obstack, it must initialize the obstack by calling
839@code{obstack_init}.
840
841@comment obstack.h
842@comment GNU
843@deftypefun int obstack_init (struct obstack *@var{obstack-ptr})
844Initialize obstack @var{obstack-ptr} for allocation of objects. This
845function calls the obstack's @code{obstack_chunk_alloc} function. It
846returns 0 if @code{obstack_chunk_alloc} returns a null pointer, meaning
847that it is out of memory. Otherwise, it returns 1. If you supply an
848@code{obstack_chunk_alloc} function that calls @code{exit}
849(@pxref{Program Termination}) or @code{longjmp} (@pxref{Non-Local
850Exits}) when out of memory, you can safely ignore the value that
851@code{obstack_init} returns.
852@end deftypefun
853
854Here are two examples of how to allocate the space for an obstack and
855initialize it. First, an obstack that is a static variable:
856
857@smallexample
858static struct obstack myobstack;
859@dots{}
860obstack_init (&myobstack);
861@end smallexample
862
863@noindent
864Second, an obstack that is itself dynamically allocated:
865
866@smallexample
867struct obstack *myobstack_ptr
868 = (struct obstack *) xmalloc (sizeof (struct obstack));
869
870obstack_init (myobstack_ptr);
871@end smallexample
872
873@node Allocation in an Obstack
874@subsection Allocation in an Obstack
875@cindex allocation (obstacks)
876
877The most direct way to allocate an object in an obstack is with
878@code{obstack_alloc}, which is invoked almost like @code{malloc}.
879
880@comment obstack.h
881@comment GNU
882@deftypefun {void *} obstack_alloc (struct obstack *@var{obstack-ptr}, int @var{size})
883This allocates an uninitialized block of @var{size} bytes in an obstack
884and returns its address. Here @var{obstack-ptr} specifies which obstack
885to allocate the block in; it is the address of the @code{struct obstack}
886object which represents the obstack. Each obstack function or macro
887requires you to specify an @var{obstack-ptr} as the first argument.
888
889This function calls the obstack's @code{obstack_chunk_alloc} function if
890it needs to allocate a new chunk of memory; it returns a null pointer if
891@code{obstack_chunk_alloc} returns one. In that case, it has not
892changed the amount of memory allocated in the obstack. If you supply an
893@code{obstack_chunk_alloc} function that calls @code{exit}
894(@pxref{Program Termination}) or @code{longjmp} (@pxref{Non-Local
895Exits}) when out of memory, then @code{obstack_alloc} will never return
896a null pointer.
897@end deftypefun
898
899For example, here is a function that allocates a copy of a string @var{str}
900in a specific obstack, which is in the variable @code{string_obstack}:
901
902@smallexample
903struct obstack string_obstack;
904
905char *
906copystring (char *string)
907@{
908 char *s = (char *) obstack_alloc (&string_obstack,
909 strlen (string) + 1);
910 memcpy (s, string, strlen (string));
911 return s;
912@}
913@end smallexample
914
915To allocate a block with specified contents, use the function
916@code{obstack_copy}, declared like this:
917
918@comment obstack.h
919@comment GNU
920@deftypefun {void *} obstack_copy (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
921This allocates a block and initializes it by copying @var{size}
922bytes of data starting at @var{address}. It can return a null pointer
923under the same conditions as @code{obstack_alloc}.
924@end deftypefun
925
926@comment obstack.h
927@comment GNU
928@deftypefun {void *} obstack_copy0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
929Like @code{obstack_copy}, but appends an extra byte containing a null
930character. This extra byte is not counted in the argument @var{size}.
931@end deftypefun
932
933The @code{obstack_copy0} function is convenient for copying a sequence
934of characters into an obstack as a null-terminated string. Here is an
935example of its use:
936
937@smallexample
938char *
939obstack_savestring (char *addr, int size)
940@{
941 return obstack_copy0 (&myobstack, addr, size);
942@}
943@end smallexample
944
945@noindent
946Contrast this with the previous example of @code{savestring} using
947@code{malloc} (@pxref{Basic Allocation}).
948
949@node Freeing Obstack Objects
950@subsection Freeing Objects in an Obstack
951@cindex freeing (obstacks)
952
953To free an object allocated in an obstack, use the function
954@code{obstack_free}. Since the obstack is a stack of objects, freeing
955one object automatically frees all other objects allocated more recently
956in the same obstack.
957
958@comment obstack.h
959@comment GNU
960@deftypefun void obstack_free (struct obstack *@var{obstack-ptr}, void *@var{object})
961If @var{object} is a null pointer, everything allocated in the obstack
962is freed. Otherwise, @var{object} must be the address of an object
963allocated in the obstack. Then @var{object} is freed, along with
964everything allocated in @var{obstack} since @var{object}.
965@end deftypefun
966
967Note that if @var{object} is a null pointer, the result is an
968uninitialized obstack. To free all storage in an obstack but leave it
969valid for further allocation, call @code{obstack_free} with the address
970of the first object allocated on the obstack:
971
972@smallexample
973obstack_free (obstack_ptr, first_object_allocated_ptr);
974@end smallexample
975
976Recall that the objects in an obstack are grouped into chunks. When all
977the objects in a chunk become free, the obstack library automatically
978frees the chunk (@pxref{Preparing for Obstacks}). Then other
979obstacks, or non-obstack allocation, can reuse the space of the chunk.
980
981@node Obstack Functions
982@subsection Obstack Functions and Macros
983@cindex macros
984
985The interfaces for using obstacks may be defined either as functions or
986as macros, depending on the compiler. The obstack facility works with
987all C compilers, including both ANSI C and traditional C, but there are
988precautions you must take if you plan to use compilers other than GNU C.
989
990If you are using an old-fashioned non-ANSI C compiler, all the obstack
991``functions'' are actually defined only as macros. You can call these
992macros like functions, but you cannot use them in any other way (for
993example, you cannot take their address).
994
995Calling the macros requires a special precaution: namely, the first
996operand (the obstack pointer) may not contain any side effects, because
997it may be computed more than once. For example, if you write this:
998
999@smallexample
1000obstack_alloc (get_obstack (), 4);
1001@end smallexample
1002
1003@noindent
1004you will find that @code{get_obstack} may be called several times.
1005If you use @code{*obstack_list_ptr++} as the obstack pointer argument,
1006you will get very strange results since the incrementation may occur
1007several times.
1008
1009In ANSI C, each function has both a macro definition and a function
1010definition. The function definition is used if you take the address of the
1011function without calling it. An ordinary call uses the macro definition by
1012default, but you can request the function definition instead by writing the
1013function name in parentheses, as shown here:
1014
1015@smallexample
1016char *x;
1017void *(*funcp) ();
1018/* @r{Use the macro}. */
1019x = (char *) obstack_alloc (obptr, size);
1020/* @r{Call the function}. */
1021x = (char *) (obstack_alloc) (obptr, size);
1022/* @r{Take the address of the function}. */
1023funcp = obstack_alloc;
1024@end smallexample
1025
1026@noindent
1027This is the same situation that exists in ANSI C for the standard library
1028functions. @xref{Macro Definitions}.
1029
1030@strong{Warning:} When you do use the macros, you must observe the
1031precaution of avoiding side effects in the first operand, even in ANSI
1032C.
1033
1034If you use the GNU C compiler, this precaution is not necessary, because
1035various language extensions in GNU C permit defining the macros so as to
1036compute each argument only once.
1037
1038@node Growing Objects
1039@subsection Growing Objects
1040@cindex growing objects (in obstacks)
1041@cindex changing the size of a block (obstacks)
1042
1043Because storage in obstack chunks is used sequentially, it is possible to
1044build up an object step by step, adding one or more bytes at a time to the
1045end of the object. With this technique, you do not need to know how much
1046data you will put in the object until you come to the end of it. We call
1047this the technique of @dfn{growing objects}. The special functions
1048for adding data to the growing object are described in this section.
1049
1050You don't need to do anything special when you start to grow an object.
1051Using one of the functions to add data to the object automatically
1052starts it. However, it is necessary to say explicitly when the object is
1053finished. This is done with the function @code{obstack_finish}.
1054
1055The actual address of the object thus built up is not known until the
1056object is finished. Until then, it always remains possible that you will
1057add so much data that the object must be copied into a new chunk.
1058
1059While the obstack is in use for a growing object, you cannot use it for
1060ordinary allocation of another object. If you try to do so, the space
1061already added to the growing object will become part of the other object.
1062
1063@comment obstack.h
1064@comment GNU
1065@deftypefun void obstack_blank (struct obstack *@var{obstack-ptr}, int @var{size})
1066The most basic function for adding to a growing object is
1067@code{obstack_blank}, which adds space without initializing it.
1068@end deftypefun
1069
1070@comment obstack.h
1071@comment GNU
1072@deftypefun void obstack_grow (struct obstack *@var{obstack-ptr}, void *@var{data}, int @var{size})
1073To add a block of initialized space, use @code{obstack_grow}, which is
1074the growing-object analogue of @code{obstack_copy}. It adds @var{size}
1075bytes of data to the growing object, copying the contents from
1076@var{data}.
1077@end deftypefun
1078
1079@comment obstack.h
1080@comment GNU
1081@deftypefun void obstack_grow0 (struct obstack *@var{obstack-ptr}, void *@var{data}, int @var{size})
1082This is the growing-object analogue of @code{obstack_copy0}. It adds
1083@var{size} bytes copied from @var{data}, followed by an additional null
1084character.
1085@end deftypefun
1086
1087@comment obstack.h
1088@comment GNU
1089@deftypefun void obstack_1grow (struct obstack *@var{obstack-ptr}, char @var{c})
1090To add one character at a time, use the function @code{obstack_1grow}.
1091It adds a single byte containing @var{c} to the growing object.
1092@end deftypefun
1093
2c6fe0bd
UD
1094@comment obstack.h
1095@comment GNU
1096@deftypefun void obstack_ptr_grow (struct obstack *@var{obstack-ptr}, void *@var{data})
1097Adding the value of a pointer one can use the function
1098@code{obstack_ptr_grow}. It adds @code{sizeof (void *)} bytes
1099containing the value of @var{data}.
1100@end deftypefun
1101
1102@comment obstack.h
1103@comment GNU
1104@deftypefun void obstack_int_grow (struct obstack *@var{obstack-ptr}, int @var{data})
1105A single value of type @code{int} can be added by using the
1106@code{obstack_int_grow} function. It adds @code{sizeof (int)} bytes to
1107the growing object and initializes them with the value of @var{data}.
1108@end deftypefun
1109
28f540f4
RM
1110@comment obstack.h
1111@comment GNU
1112@deftypefun {void *} obstack_finish (struct obstack *@var{obstack-ptr})
1113When you are finished growing the object, use the function
1114@code{obstack_finish} to close it off and return its final address.
1115
1116Once you have finished the object, the obstack is available for ordinary
1117allocation or for growing another object.
1118
1119This function can return a null pointer under the same conditions as
1120@code{obstack_alloc} (@pxref{Allocation in an Obstack}).
1121@end deftypefun
1122
1123When you build an object by growing it, you will probably need to know
1124afterward how long it became. You need not keep track of this as you grow
1125the object, because you can find out the length from the obstack just
1126before finishing the object with the function @code{obstack_object_size},
1127declared as follows:
1128
1129@comment obstack.h
1130@comment GNU
1131@deftypefun int obstack_object_size (struct obstack *@var{obstack-ptr})
1132This function returns the current size of the growing object, in bytes.
1133Remember to call this function @emph{before} finishing the object.
1134After it is finished, @code{obstack_object_size} will return zero.
1135@end deftypefun
1136
1137If you have started growing an object and wish to cancel it, you should
1138finish it and then free it, like this:
1139
1140@smallexample
1141obstack_free (obstack_ptr, obstack_finish (obstack_ptr));
1142@end smallexample
1143
1144@noindent
1145This has no effect if no object was growing.
1146
1147@cindex shrinking objects
1148You can use @code{obstack_blank} with a negative size argument to make
1149the current object smaller. Just don't try to shrink it beyond zero
1150length---there's no telling what will happen if you do that.
1151
1152@node Extra Fast Growing
1153@subsection Extra Fast Growing Objects
1154@cindex efficiency and obstacks
1155
1156The usual functions for growing objects incur overhead for checking
1157whether there is room for the new growth in the current chunk. If you
1158are frequently constructing objects in small steps of growth, this
1159overhead can be significant.
1160
1161You can reduce the overhead by using special ``fast growth''
1162functions that grow the object without checking. In order to have a
1163robust program, you must do the checking yourself. If you do this checking
1164in the simplest way each time you are about to add data to the object, you
1165have not saved anything, because that is what the ordinary growth
1166functions do. But if you can arrange to check less often, or check
1167more efficiently, then you make the program faster.
1168
1169The function @code{obstack_room} returns the amount of room available
1170in the current chunk. It is declared as follows:
1171
1172@comment obstack.h
1173@comment GNU
1174@deftypefun int obstack_room (struct obstack *@var{obstack-ptr})
1175This returns the number of bytes that can be added safely to the current
1176growing object (or to an object about to be started) in obstack
1177@var{obstack} using the fast growth functions.
1178@end deftypefun
1179
1180While you know there is room, you can use these fast growth functions
1181for adding data to a growing object:
1182
1183@comment obstack.h
1184@comment GNU
1185@deftypefun void obstack_1grow_fast (struct obstack *@var{obstack-ptr}, char @var{c})
1186The function @code{obstack_1grow_fast} adds one byte containing the
1187character @var{c} to the growing object in obstack @var{obstack-ptr}.
1188@end deftypefun
1189
2c6fe0bd
UD
1190@comment obstack.h
1191@comment GNU
1192@deftypefun void obstack_ptr_grow_fast (struct obstack *@var{obstack-ptr}, void *@var{data})
1193The function @code{obstack_ptr_grow_fast} adds @code{sizeof (void *)}
1194bytes containing the value of @var{data} to the growing object in
1195obstack @var{obstack-ptr}.
1196@end deftypefun
1197
1198@comment obstack.h
1199@comment GNU
1200@deftypefun void obstack_int_grow_fast (struct obstack *@var{obstack-ptr}, int @var{data})
1201The function @code{obstack_int_grow_fast} adds @code{sizeof (int)} bytes
1202containing the value of @var{data} to the growing object in obstack
1203@var{obstack-ptr}.
1204@end deftypefun
1205
28f540f4
RM
1206@comment obstack.h
1207@comment GNU
1208@deftypefun void obstack_blank_fast (struct obstack *@var{obstack-ptr}, int @var{size})
1209The function @code{obstack_blank_fast} adds @var{size} bytes to the
1210growing object in obstack @var{obstack-ptr} without initializing them.
1211@end deftypefun
1212
1213When you check for space using @code{obstack_room} and there is not
1214enough room for what you want to add, the fast growth functions
1215are not safe. In this case, simply use the corresponding ordinary
1216growth function instead. Very soon this will copy the object to a
a5113b14 1217new chunk; then there will be lots of room available again.
28f540f4
RM
1218
1219So, each time you use an ordinary growth function, check afterward for
1220sufficient space using @code{obstack_room}. Once the object is copied
1221to a new chunk, there will be plenty of space again, so the program will
1222start using the fast growth functions again.
1223
1224Here is an example:
1225
1226@smallexample
1227@group
1228void
1229add_string (struct obstack *obstack, const char *ptr, int len)
1230@{
1231 while (len > 0)
1232 @{
1233 int room = obstack_room (obstack);
1234 if (room == 0)
1235 @{
1236 /* @r{Not enough room. Add one character slowly,}
1237 @r{which may copy to a new chunk and make room.} */
1238 obstack_1grow (obstack, *ptr++);
1239 len--;
1240 @}
a5113b14 1241 else
28f540f4
RM
1242 @{
1243 if (room > len)
1244 room = len;
1245 /* @r{Add fast as much as we have room for.} */
1246 len -= room;
1247 while (room-- > 0)
1248 obstack_1grow_fast (obstack, *ptr++);
1249 @}
1250 @}
1251@}
1252@end group
1253@end smallexample
1254
1255@node Status of an Obstack
1256@subsection Status of an Obstack
1257@cindex obstack status
1258@cindex status of obstack
1259
1260Here are functions that provide information on the current status of
1261allocation in an obstack. You can use them to learn about an object while
1262still growing it.
1263
1264@comment obstack.h
1265@comment GNU
1266@deftypefun {void *} obstack_base (struct obstack *@var{obstack-ptr})
1267This function returns the tentative address of the beginning of the
1268currently growing object in @var{obstack-ptr}. If you finish the object
1269immediately, it will have that address. If you make it larger first, it
1270may outgrow the current chunk---then its address will change!
1271
1272If no object is growing, this value says where the next object you
1273allocate will start (once again assuming it fits in the current
1274chunk).
1275@end deftypefun
1276
1277@comment obstack.h
1278@comment GNU
1279@deftypefun {void *} obstack_next_free (struct obstack *@var{obstack-ptr})
1280This function returns the address of the first free byte in the current
1281chunk of obstack @var{obstack-ptr}. This is the end of the currently
1282growing object. If no object is growing, @code{obstack_next_free}
1283returns the same value as @code{obstack_base}.
1284@end deftypefun
1285
1286@comment obstack.h
1287@comment GNU
1288@deftypefun int obstack_object_size (struct obstack *@var{obstack-ptr})
1289This function returns the size in bytes of the currently growing object.
1290This is equivalent to
1291
1292@smallexample
1293obstack_next_free (@var{obstack-ptr}) - obstack_base (@var{obstack-ptr})
1294@end smallexample
1295@end deftypefun
1296
1297@node Obstacks Data Alignment
1298@subsection Alignment of Data in Obstacks
1299@cindex alignment (in obstacks)
1300
1301Each obstack has an @dfn{alignment boundary}; each object allocated in
1302the obstack automatically starts on an address that is a multiple of the
1303specified boundary. By default, this boundary is 4 bytes.
1304
1305To access an obstack's alignment boundary, use the macro
1306@code{obstack_alignment_mask}, whose function prototype looks like
1307this:
1308
1309@comment obstack.h
1310@comment GNU
1311@deftypefn Macro int obstack_alignment_mask (struct obstack *@var{obstack-ptr})
1312The value is a bit mask; a bit that is 1 indicates that the corresponding
1313bit in the address of an object should be 0. The mask value should be one
1314less than a power of 2; the effect is that all object addresses are
1315multiples of that power of 2. The default value of the mask is 3, so that
1316addresses are multiples of 4. A mask value of 0 means an object can start
1317on any multiple of 1 (that is, no alignment is required).
1318
1319The expansion of the macro @code{obstack_alignment_mask} is an lvalue,
1320so you can alter the mask by assignment. For example, this statement:
1321
1322@smallexample
1323obstack_alignment_mask (obstack_ptr) = 0;
1324@end smallexample
1325
1326@noindent
1327has the effect of turning off alignment processing in the specified obstack.
1328@end deftypefn
1329
1330Note that a change in alignment mask does not take effect until
1331@emph{after} the next time an object is allocated or finished in the
1332obstack. If you are not growing an object, you can make the new
1333alignment mask take effect immediately by calling @code{obstack_finish}.
1334This will finish a zero-length object and then do proper alignment for
1335the next object.
1336
1337@node Obstack Chunks
1338@subsection Obstack Chunks
1339@cindex efficiency of chunks
1340@cindex chunks
1341
1342Obstacks work by allocating space for themselves in large chunks, and
1343then parceling out space in the chunks to satisfy your requests. Chunks
1344are normally 4096 bytes long unless you specify a different chunk size.
1345The chunk size includes 8 bytes of overhead that are not actually used
1346for storing objects. Regardless of the specified size, longer chunks
1347will be allocated when necessary for long objects.
1348
1349The obstack library allocates chunks by calling the function
1350@code{obstack_chunk_alloc}, which you must define. When a chunk is no
1351longer needed because you have freed all the objects in it, the obstack
1352library frees the chunk by calling @code{obstack_chunk_free}, which you
1353must also define.
1354
1355These two must be defined (as macros) or declared (as functions) in each
1356source file that uses @code{obstack_init} (@pxref{Creating Obstacks}).
1357Most often they are defined as macros like this:
1358
1359@smallexample
1360#define obstack_chunk_alloc xmalloc
1361#define obstack_chunk_free free
1362@end smallexample
1363
1364Note that these are simple macros (no arguments). Macro definitions with
1365arguments will not work! It is necessary that @code{obstack_chunk_alloc}
1366or @code{obstack_chunk_free}, alone, expand into a function name if it is
1367not itself a function name.
1368
1369If you allocate chunks with @code{malloc}, the chunk size should be a
1370power of 2. The default chunk size, 4096, was chosen because it is long
1371enough to satisfy many typical requests on the obstack yet short enough
1372not to waste too much memory in the portion of the last chunk not yet used.
1373
1374@comment obstack.h
1375@comment GNU
1376@deftypefn Macro int obstack_chunk_size (struct obstack *@var{obstack-ptr})
1377This returns the chunk size of the given obstack.
1378@end deftypefn
1379
1380Since this macro expands to an lvalue, you can specify a new chunk size by
1381assigning it a new value. Doing so does not affect the chunks already
1382allocated, but will change the size of chunks allocated for that particular
1383obstack in the future. It is unlikely to be useful to make the chunk size
1384smaller, but making it larger might improve efficiency if you are
1385allocating many objects whose size is comparable to the chunk size. Here
1386is how to do so cleanly:
1387
1388@smallexample
1389if (obstack_chunk_size (obstack_ptr) < @var{new-chunk-size})
1390 obstack_chunk_size (obstack_ptr) = @var{new-chunk-size};
1391@end smallexample
1392
1393@node Summary of Obstacks
1394@subsection Summary of Obstack Functions
1395
1396Here is a summary of all the functions associated with obstacks. Each
1397takes the address of an obstack (@code{struct obstack *}) as its first
1398argument.
1399
1400@table @code
1401@item void obstack_init (struct obstack *@var{obstack-ptr})
1402Initialize use of an obstack. @xref{Creating Obstacks}.
1403
1404@item void *obstack_alloc (struct obstack *@var{obstack-ptr}, int @var{size})
1405Allocate an object of @var{size} uninitialized bytes.
1406@xref{Allocation in an Obstack}.
1407
1408@item void *obstack_copy (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1409Allocate an object of @var{size} bytes, with contents copied from
1410@var{address}. @xref{Allocation in an Obstack}.
1411
1412@item void *obstack_copy0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1413Allocate an object of @var{size}+1 bytes, with @var{size} of them copied
1414from @var{address}, followed by a null character at the end.
1415@xref{Allocation in an Obstack}.
1416
1417@item void obstack_free (struct obstack *@var{obstack-ptr}, void *@var{object})
1418Free @var{object} (and everything allocated in the specified obstack
1419more recently than @var{object}). @xref{Freeing Obstack Objects}.
1420
1421@item void obstack_blank (struct obstack *@var{obstack-ptr}, int @var{size})
1422Add @var{size} uninitialized bytes to a growing object.
1423@xref{Growing Objects}.
1424
1425@item void obstack_grow (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1426Add @var{size} bytes, copied from @var{address}, to a growing object.
1427@xref{Growing Objects}.
1428
1429@item void obstack_grow0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1430Add @var{size} bytes, copied from @var{address}, to a growing object,
1431and then add another byte containing a null character. @xref{Growing
1432Objects}.
1433
1434@item void obstack_1grow (struct obstack *@var{obstack-ptr}, char @var{data-char})
1435Add one byte containing @var{data-char} to a growing object.
1436@xref{Growing Objects}.
1437
1438@item void *obstack_finish (struct obstack *@var{obstack-ptr})
1439Finalize the object that is growing and return its permanent address.
1440@xref{Growing Objects}.
1441
1442@item int obstack_object_size (struct obstack *@var{obstack-ptr})
1443Get the current size of the currently growing object. @xref{Growing
1444Objects}.
1445
1446@item void obstack_blank_fast (struct obstack *@var{obstack-ptr}, int @var{size})
1447Add @var{size} uninitialized bytes to a growing object without checking
1448that there is enough room. @xref{Extra Fast Growing}.
1449
1450@item void obstack_1grow_fast (struct obstack *@var{obstack-ptr}, char @var{data-char})
1451Add one byte containing @var{data-char} to a growing object without
1452checking that there is enough room. @xref{Extra Fast Growing}.
1453
1454@item int obstack_room (struct obstack *@var{obstack-ptr})
1455Get the amount of room now available for growing the current object.
1456@xref{Extra Fast Growing}.
1457
1458@item int obstack_alignment_mask (struct obstack *@var{obstack-ptr})
1459The mask used for aligning the beginning of an object. This is an
1460lvalue. @xref{Obstacks Data Alignment}.
1461
1462@item int obstack_chunk_size (struct obstack *@var{obstack-ptr})
1463The size for allocating chunks. This is an lvalue. @xref{Obstack Chunks}.
1464
1465@item void *obstack_base (struct obstack *@var{obstack-ptr})
1466Tentative starting address of the currently growing object.
1467@xref{Status of an Obstack}.
1468
1469@item void *obstack_next_free (struct obstack *@var{obstack-ptr})
1470Address just after the end of the currently growing object.
1471@xref{Status of an Obstack}.
1472@end table
1473
1474@node Variable Size Automatic
1475@section Automatic Storage with Variable Size
1476@cindex automatic freeing
1477@cindex @code{alloca} function
1478@cindex automatic storage with variable size
1479
1480The function @code{alloca} supports a kind of half-dynamic allocation in
1481which blocks are allocated dynamically but freed automatically.
1482
1483Allocating a block with @code{alloca} is an explicit action; you can
1484allocate as many blocks as you wish, and compute the size at run time. But
1485all the blocks are freed when you exit the function that @code{alloca} was
1486called from, just as if they were automatic variables declared in that
1487function. There is no way to free the space explicitly.
1488
1489The prototype for @code{alloca} is in @file{stdlib.h}. This function is
1490a BSD extension.
1491@pindex stdlib.h
1492
1493@comment stdlib.h
1494@comment GNU, BSD
1495@deftypefun {void *} alloca (size_t @var{size});
1496The return value of @code{alloca} is the address of a block of @var{size}
1497bytes of storage, allocated in the stack frame of the calling function.
1498@end deftypefun
1499
1500Do not use @code{alloca} inside the arguments of a function call---you
1501will get unpredictable results, because the stack space for the
1502@code{alloca} would appear on the stack in the middle of the space for
1503the function arguments. An example of what to avoid is @code{foo (x,
1504alloca (4), y)}.
1505@c This might get fixed in future versions of GCC, but that won't make
1506@c it safe with compilers generally.
1507
1508@menu
1509* Alloca Example:: Example of using @code{alloca}.
1510* Advantages of Alloca:: Reasons to use @code{alloca}.
1511* Disadvantages of Alloca:: Reasons to avoid @code{alloca}.
1512* GNU C Variable-Size Arrays:: Only in GNU C, here is an alternative
1513 method of allocating dynamically and
1514 freeing automatically.
1515@end menu
1516
1517@node Alloca Example
1518@subsection @code{alloca} Example
1519
1520As an example of use of @code{alloca}, here is a function that opens a file
1521name made from concatenating two argument strings, and returns a file
1522descriptor or minus one signifying failure:
1523
1524@smallexample
1525int
1526open2 (char *str1, char *str2, int flags, int mode)
1527@{
1528 char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
a5113b14 1529 stpcpy (stpcpy (name, str1), str2);
28f540f4
RM
1530 return open (name, flags, mode);
1531@}
1532@end smallexample
1533
1534@noindent
1535Here is how you would get the same results with @code{malloc} and
1536@code{free}:
1537
1538@smallexample
1539int
1540open2 (char *str1, char *str2, int flags, int mode)
1541@{
1542 char *name = (char *) malloc (strlen (str1) + strlen (str2) + 1);
1543 int desc;
1544 if (name == 0)
1545 fatal ("virtual memory exceeded");
a5113b14 1546 stpcpy (stpcpy (name, str1), str2);
28f540f4
RM
1547 desc = open (name, flags, mode);
1548 free (name);
1549 return desc;
1550@}
1551@end smallexample
1552
1553As you can see, it is simpler with @code{alloca}. But @code{alloca} has
1554other, more important advantages, and some disadvantages.
1555
1556@node Advantages of Alloca
1557@subsection Advantages of @code{alloca}
1558
1559Here are the reasons why @code{alloca} may be preferable to @code{malloc}:
1560
1561@itemize @bullet
1562@item
1563Using @code{alloca} wastes very little space and is very fast. (It is
1564open-coded by the GNU C compiler.)
1565
1566@item
1567Since @code{alloca} does not have separate pools for different sizes of
1568block, space used for any size block can be reused for any other size.
1569@code{alloca} does not cause storage fragmentation.
1570
1571@item
1572@cindex longjmp
1573Nonlocal exits done with @code{longjmp} (@pxref{Non-Local Exits})
1574automatically free the space allocated with @code{alloca} when they exit
1575through the function that called @code{alloca}. This is the most
1576important reason to use @code{alloca}.
1577
1578To illustrate this, suppose you have a function
1579@code{open_or_report_error} which returns a descriptor, like
1580@code{open}, if it succeeds, but does not return to its caller if it
1581fails. If the file cannot be opened, it prints an error message and
1582jumps out to the command level of your program using @code{longjmp}.
1583Let's change @code{open2} (@pxref{Alloca Example}) to use this
1584subroutine:@refill
1585
1586@smallexample
1587int
1588open2 (char *str1, char *str2, int flags, int mode)
1589@{
1590 char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
a5113b14 1591 stpcpy (stpcpy (name, str1), str2);
28f540f4
RM
1592 return open_or_report_error (name, flags, mode);
1593@}
1594@end smallexample
1595
1596@noindent
1597Because of the way @code{alloca} works, the storage it allocates is
1598freed even when an error occurs, with no special effort required.
1599
1600By contrast, the previous definition of @code{open2} (which uses
1601@code{malloc} and @code{free}) would develop a storage leak if it were
1602changed in this way. Even if you are willing to make more changes to
1603fix it, there is no easy way to do so.
1604@end itemize
1605
1606@node Disadvantages of Alloca
1607@subsection Disadvantages of @code{alloca}
1608
1609@cindex @code{alloca} disadvantages
1610@cindex disadvantages of @code{alloca}
1611These are the disadvantages of @code{alloca} in comparison with
1612@code{malloc}:
1613
1614@itemize @bullet
1615@item
1616If you try to allocate more storage than the machine can provide, you
1617don't get a clean error message. Instead you get a fatal signal like
1618the one you would get from an infinite recursion; probably a
1619segmentation violation (@pxref{Program Error Signals}).
1620
1621@item
1622Some non-GNU systems fail to support @code{alloca}, so it is less
1623portable. However, a slower emulation of @code{alloca} written in C
1624is available for use on systems with this deficiency.
1625@end itemize
1626
1627@node GNU C Variable-Size Arrays
1628@subsection GNU C Variable-Size Arrays
1629@cindex variable-sized arrays
1630
1631In GNU C, you can replace most uses of @code{alloca} with an array of
1632variable size. Here is how @code{open2} would look then:
1633
1634@smallexample
1635int open2 (char *str1, char *str2, int flags, int mode)
1636@{
1637 char name[strlen (str1) + strlen (str2) + 1];
a5113b14 1638 stpcpy (stpcpy (name, str1), str2);
28f540f4
RM
1639 return open (name, flags, mode);
1640@}
1641@end smallexample
1642
1643But @code{alloca} is not always equivalent to a variable-sized array, for
1644several reasons:
1645
1646@itemize @bullet
1647@item
1648A variable size array's space is freed at the end of the scope of the
1649name of the array. The space allocated with @code{alloca}
1650remains until the end of the function.
1651
1652@item
1653It is possible to use @code{alloca} within a loop, allocating an
1654additional block on each iteration. This is impossible with
1655variable-sized arrays.
1656@end itemize
1657
1658@strong{Note:} If you mix use of @code{alloca} and variable-sized arrays
1659within one function, exiting a scope in which a variable-sized array was
1660declared frees all blocks allocated with @code{alloca} during the
1661execution of that scope.
1662
1663
1664@node Relocating Allocator
1665@section Relocating Allocator
1666
1667@cindex relocating memory allocator
1668Any system of dynamic memory allocation has overhead: the amount of
1669space it uses is more than the amount the program asks for. The
1670@dfn{relocating memory allocator} achieves very low overhead by moving
1671blocks in memory as necessary, on its own initiative.
1672
1673@menu
1674* Relocator Concepts:: How to understand relocating allocation.
1675* Using Relocator:: Functions for relocating allocation.
1676@end menu
1677
1678@node Relocator Concepts
1679@subsection Concepts of Relocating Allocation
1680
1681@ifinfo
1682The @dfn{relocating memory allocator} achieves very low overhead by
1683moving blocks in memory as necessary, on its own initiative.
1684@end ifinfo
1685
1686When you allocate a block with @code{malloc}, the address of the block
1687never changes unless you use @code{realloc} to change its size. Thus,
1688you can safely store the address in various places, temporarily or
1689permanently, as you like. This is not safe when you use the relocating
1690memory allocator, because any and all relocatable blocks can move
1691whenever you allocate memory in any fashion. Even calling @code{malloc}
1692or @code{realloc} can move the relocatable blocks.
1693
1694@cindex handle
1695For each relocatable block, you must make a @dfn{handle}---a pointer
1696object in memory, designated to store the address of that block. The
1697relocating allocator knows where each block's handle is, and updates the
1698address stored there whenever it moves the block, so that the handle
1699always points to the block. Each time you access the contents of the
1700block, you should fetch its address anew from the handle.
1701
1702To call any of the relocating allocator functions from a signal handler
1703is almost certainly incorrect, because the signal could happen at any
1704time and relocate all the blocks. The only way to make this safe is to
1705block the signal around any access to the contents of any relocatable
1706block---not a convenient mode of operation. @xref{Nonreentrancy}.
1707
1708@node Using Relocator
1709@subsection Allocating and Freeing Relocatable Blocks
1710
1711@pindex malloc.h
1712In the descriptions below, @var{handleptr} designates the address of the
1713handle. All the functions are declared in @file{malloc.h}; all are GNU
1714extensions.
1715
1716@comment malloc.h
1717@comment GNU
1718@deftypefun {void *} r_alloc (void **@var{handleptr}, size_t @var{size})
1719This function allocates a relocatable block of size @var{size}. It
1720stores the block's address in @code{*@var{handleptr}} and returns
1721a non-null pointer to indicate success.
1722
1723If @code{r_alloc} can't get the space needed, it stores a null pointer
1724in @code{*@var{handleptr}}, and returns a null pointer.
1725@end deftypefun
1726
1727@comment malloc.h
1728@comment GNU
1729@deftypefun void r_alloc_free (void **@var{handleptr})
1730This function is the way to free a relocatable block. It frees the
1731block that @code{*@var{handleptr}} points to, and stores a null pointer
1732in @code{*@var{handleptr}} to show it doesn't point to an allocated
1733block any more.
1734@end deftypefun
1735
1736@comment malloc.h
1737@comment GNU
1738@deftypefun {void *} r_re_alloc (void **@var{handleptr}, size_t @var{size})
1739The function @code{r_re_alloc} adjusts the size of the block that
1740@code{*@var{handleptr}} points to, making it @var{size} bytes long. It
1741stores the address of the resized block in @code{*@var{handleptr}} and
1742returns a non-null pointer to indicate success.
1743
1744If enough memory is not available, this function returns a null pointer
1745and does not modify @code{*@var{handleptr}}.
1746@end deftypefun
1747
1748@node Memory Warnings
1749@section Memory Usage Warnings
1750@cindex memory usage warnings
1751@cindex warnings of memory almost full
1752
1753@pindex malloc.c
1754You can ask for warnings as the program approaches running out of memory
1755space, by calling @code{memory_warnings}. This tells @code{malloc} to
1756check memory usage every time it asks for more memory from the operating
1757system. This is a GNU extension declared in @file{malloc.h}.
1758
1759@comment malloc.h
1760@comment GNU
1761@deftypefun void memory_warnings (void *@var{start}, void (*@var{warn-func}) (const char *))
1762Call this function to request warnings for nearing exhaustion of virtual
1763memory.
1764
1765The argument @var{start} says where data space begins, in memory. The
1766allocator compares this against the last address used and against the
1767limit of data space, to determine the fraction of available memory in
1768use. If you supply zero for @var{start}, then a default value is used
1769which is right in most circumstances.
1770
1771For @var{warn-func}, supply a function that @code{malloc} can call to
1772warn you. It is called with a string (a warning message) as argument.
1773Normally it ought to display the string for the user to read.
1774@end deftypefun
1775
1776The warnings come when memory becomes 75% full, when it becomes 85%
1777full, and when it becomes 95% full. Above 95% you get another warning
1778each time memory usage increases.