@Go to the ‰ŠP�”›first@�”˜, ‰ŠP�”›previous@�”˜, ‰ŠP�”›next@�”˜, ‰ŠP�”›last@�”˜ section, ‰ŠP�”›table of contents@�”˜.
Œ

ˆ‰SEC18Št�”›Memory Allocation

‰IDX202Š‰IDX203Š
@�”˜The GNU system provides several methods for allocating memory space under explicit program control. They vary in generality and in efficiency. þÂ
• The Hmalloc@ facility allows fully general dynamic allocation. See section ‰ŠP�”›Unconstrained Allocation@�”˜.
• Obstacks are another facility, less general than Hmalloc@ but more efficient and convenient for stacklike allocation. See section ‰ŠP�”›Obstacks@�”˜.
• The function Halloca@ lets you allocate storage dynamically that will be freed automatically. See section ‰ŠP�”›Automatic Storage with Variable Size@�”˜.Àð
ˆ‰SEC19Št�”›Dynamic Memory Allocation Concepts

‰IDX204Š‰IDX205Š‰IDX206Š
B�”˜Dynamic memory allocation@ is a technique in which programs determine as they are running where to store some information. You need dynamic allocation when the number of memory blocks you need, or how long you continue to need them, depends on the data you are working on.
For example, you may need a block to store a line read from an input file; since there is no limit to how long a line can be, you must allocate the storage dynamically and make it dynamically larger as you read more of the line.
Or, you may need a block for each record or each definition in the input data; since you can't know in advance how many there will be, you must allocate a new block for each record or definition as you read it.
When you use dynamic allocation, the allocation of a block of memory is an action that the program requests explicitly. You call a function or macro when you want to allocate space, and specify the size with an argument. If you want to free the space, you do so by calling another function or macro. You can do these things whenever you want, as often as you want.
ˆ‰SEC20Št�”›Dynamic Allocation and C

@�”˜The C language supports two kinds of memory allocation through the variables in C programs: þÂ
• BStatic allocation@ is what happens when you declare a static or global variable. Each static or global variable defines one block of space, of a fixed size. The space is allocated once, when your program is started, and is never freed.
• BAutomatic allocation@ happens when you declare an automatic variable, such as a function argument or a local variable. The space for an automatic variable is allocated when the compound statement containing the declaration is entered, and is freed when that compound statement is exited. In GNU C, the length of the automatic storage can be an expression that varies. In other C implementations, it must be a constant.Àð
Dynamic allocation is not supported by C variables; there is no storage class "dynamic", and there can never be a C variable whose value is stored in dynamically allocated space. The only way to refer to dynamically allocated space is through a pointer. Because it is less convenient, and because the actual process of dynamic allocation requires more computation time, programmers generally use dynamic allocation only when neither static nor automatic allocation will serve.
For example, if you want to allocate dynamically some space to hold a Hstruct foobar@, you cannot declare a variable of type Hstruct foobar@ whose contents are the dynamically allocated space. But you can declare a variable of pointer type Hstruct foobar *@ and assign it the address of the space. Then you can use the operators H`*'@ and H`->'@ on this pointer variable to refer to the contents of the space: {
struct foobar *ptr
= (struct foobar *) malloc (sizeof (struct foobar));
ptr->name = x;
ptr->next = current_foobar;
current_foobar = ptr;
}
ˆ‰SEC21Št�”›Unconstrained Allocation

‰IDX207Š‰IDX208Š‰IDX209Š
@�”˜The most general dynamic allocation facility is Hmalloc@. It allows you to allocate blocks of memory of any size at any time, make them bigger or smaller at any time, and free the blocks individually at any time (or never).
ˆ‰SEC22ŠT�”›Basic Storage Allocation

‰IDX210Š
@�”˜To allocate a block of memory, call Hmalloc@. The prototype for this function is in H`stdlib.h'@. ‰IDX211Š

A�”˜Function:@ void * Dmalloc@ B(size_t Bsize@)
Â‰IDX212Š@�”˜This function returns a pointer to a newly allocated block Bsize@ bytes long, or a null pointer if the block could not be allocated.À

The contents of the block are undefined; you must initialize it yourself (or use Hcalloc@ instead; see section ‰ŠP�”›Allocating Cleared Space@�”˜). Normally you would cast the value as a pointer to the kind of object that you want to store in the block. Here we show an example of doing so, and of initializing the space with zeros using the library function Hmemset@ (see section ‰ŠP�”›Copying and Concatenation@�”˜): struct foo *ptr;
...
ptr = (struct foo *) malloc (sizeof (struct foo));
if (ptr == 0) abort ();
memset (ptr, 0, sizeof (struct foo));
You can store the result of Hmalloc@ into any pointer variable without a cast, because ISO C automatically converts the type Hvoid *@ to another type of pointer when necessary. But the cast is necessary in contexts other than assignment operators or if you might want your code to run in traditional C.
Remember that when allocating space for a string, the argument to Hmalloc@ must be one plus the length of the string. This is because a string is terminated with a null character that doesn't count in the "length" of the string but does need space. For example: char *ptr;
...
ptr = (char *) malloc (length + 1);
See section ‰ŠP�”›Representation of Strings@�”˜, for more information about this.
ˆ‰SEC23ŠT�”›Examples of \malloc

@�”˜If no more space is available, Hmalloc@ returns a null pointer. You should check the value of Bevery@ call to Hmalloc@. It is useful to write a subroutine that calls Hmalloc@ and reports an error if the value is a null pointer, returning only if the value is nonzero. This function is conventionally called Hxmalloc@. Here it is: void *
xmalloc (size_t size)
{
register void *value = malloc (size);
if (value == 0)
fatal ("virtual memory exhausted");
return value;
}
Here is a real example of using Hmalloc@ (by way of Hxmalloc@). The function Hsavestring@ will copy a sequence of characters into a newly allocated null-terminated string: char *
savestring (const char *ptr, size_t len)
{
register char *value = (char *) xmalloc (len + 1);
memcpy (value, ptr, len);
value[len] = '\0';
return value;
}
The block that Hmalloc@ gives you is guaranteed to be aligned so that it can hold any type of data. In the GNU system, the address is always a multiple of eight on most systems, and a multiple of 16 on 64-bit systems. Only rarely is any higher boundary (such as a page boundary) necessary; for those cases, use Hmemalign@ or Hvalloc@ (see section ‰ŠP�”›Allocating Aligned Memory Blocks@�”˜).
Note that the memory located after the end of the block is likely to be in use for something else; perhaps a block already allocated by another call to Hmalloc@. If you attempt to treat the block as longer than you asked for it to be, you are liable to destroy the data that Hmalloc@ uses to keep track of its blocks, or you may destroy the contents of another block. If you have already allocated a block and discover you want it to be bigger, use Hrealloc@ (see section ‰ŠP�”›Changing the Size of a Block@�”˜).
ˆ‰SEC24ŠT�”›Freeing Memory Allocated with \malloc

‰IDX213Š‰IDX214Š
@�”˜When you no longer need a block that you got with Hmalloc@, use the function Hfree@ to make the block available to be allocated again. The prototype for this function is in H`stdlib.h'@. ‰IDX215Š

A�”˜Function:@ void Dfree@ B(void *Bptr@)
Â‰IDX216Š@�”˜The Hfree@ function deallocates the block of storage pointed at by Bptr@.À

AFunction:@ void Dcfree@ B(void *Bptr@)
Â‰IDX217Š@�”˜This function does the same thing as Hfree@. It's provided for backward compatibility with SunOS; you should use Hfree@ instead.À

Freeing a block alters the contents of the block. DDo not expect to find any data (such as a pointer to the next block in a chain of blocks) in the block after freeing it.@ Copy whatever you need out of the block before freeing it! Here is an example of the proper way to free all the blocks in a chain, and the strings that they point to: struct chain
{
struct chain *next;
char *name;
}

void
free_chain (struct chain *chain)
{
while (chain != 0)
{
struct chain *next = chain->next;
free (chain->name);
free (chain);
chain = next;
}
}
Occasionally, Hfree@ can actually return memory to the operating system and make the process smaller. Usually, all it can do is allow a later call to Hmalloc@ to reuse the space. In the meantime, the space remains in your program as part of a free-list used internally by Hmalloc@.
There is no point in freeing blocks at the end of a program, because all of the program's space is given back to the system when the process terminates.
ˆ‰SEC25ŠT�”›Changing the Size of a Block

‰IDX218Š
@�”˜Often you do not know for certain how big a block you will ultimately need at the time you must begin to use the block. For example, the block might be a buffer that you use to hold a line being read from a file; no matter how long you make the buffer initially, you may encounter a line that is longer.
You can make the block longer by calling Hrealloc@. This function is declared in H`stdlib.h'@. ‰IDX219Š

A�”˜Function:@ void * Drealloc@ B(void *Bptr@, size_t Bnewsize@)
Â‰IDX220Š@�”˜The Hrealloc@ function changes the size of the block whose address is Bptr@ to be Bnewsize@.
Since the space after the end of the block may be in use, Hrealloc@ may find it necessary to copy the block to a new address where more free space is available. The value of Hrealloc@ is the new address of the block. If the block needs to be moved, Hrealloc@ copies the old contents.
If you pass a null pointer for Bptr@, Hrealloc@ behaves just like H`malloc (JnewsizeH)'@. This can be convenient, but beware that older implementations (before ISO C) may not support this behavior, and will probably crash when Hrealloc@ is passed a null pointer.À

Like Hmalloc@, Hrealloc@ may return a null pointer if no memory space is available to make the block bigger. When this happens, the original block is untouched; it has not been modified or relocated.
In most cases it makes no difference what happens to the original block when Hrealloc@ fails, because the application program cannot continue when it is out of memory, and the only thing to do is to give a fatal error message. Often it is convenient to write and use a subroutine, conventionally called Hxrealloc@, that takes care of the error message as Hxmalloc@ does for Hmalloc@: void *
xrealloc (void *ptr, size_t size)
{
register void *value = realloc (ptr, size);
if (value == 0)
fatal ("Virtual memory exhausted");
return value;
}
You can also use Hrealloc@ to make a block smaller. The reason you is needed. In several allocation implementations, making a block smaller sometimes necessitates copying it, so it can fail if no other space is available.
If the new size you specify is the same as the old size, Hrealloc@ is guaranteed to change nothing and return the same address that you gave.
ˆ‰SEC26ŠT�”›Allocating Cleared Space

@�”˜The function Hcalloc@ allocates memory and clears it to zero. It is declared in H`stdlib.h'@. ‰IDX221Š

A�”˜Function:@ void * Dcalloc@ B(size_t Bcount@, size_t Beltsize@)
Â‰IDX222Š@�”˜This function allocates a block long enough to contain a vector of Bcount@ elements, each of size Beltsize@. Its contents are cleared to zero before Hcalloc@ returns.À

You could define Hcalloc@ as follows: void *
calloc (size_t count, size_t eltsize)
{
size_t size = count * eltsize;
void *value = malloc (size);
if (value != 0)
memset (value, 0, size);
return value;
}
But in general, it is not guaranteed that Hcalloc@ calls Hmalloc@ internally. Therefore, if an application provides its own Hmalloc@/Hrealloc@/Hfree@ outside the C library, it should always define Hcalloc@, too.
ˆ‰SEC27ŠT�”›Efficiency Considerations for \malloc

‰IDX223Š
@�”˜As apposed to other versions, the Hmalloc@ in GNU libc does not round up block sizes to powers of two, neither for large nor for small sizes. Neighboring chunks can be coalesced on a Hfree@ no matter what their size is. This makes the implementation suitable for all kinds of allocation patterns without generally incurring high memory waste through fragmentation.
Very large blocks (much larger than a page) are allocated with Hmmap@ (anonymous or via H/dev/zero@) by this implementation. This has the great advantage that these chunks are returned to the system immediately when they are freed. Therefore, it cannot happen that a large chunk becomes "locked" in between smaller ones and even after calling Hfree@ wastes memory. The size threshold for Hmmap@ to be used can be adjusted with Hmallopt@. The use of Hmmap@ can also be disabled completely.
ˆ‰SEC28ŠT�”›Allocating Aligned Memory Blocks

‰IDX224Š‰IDX225Š‰IDX226Š@�”˜The address of a block returned by Hmalloc@ or Hrealloc@ in the GNU system is always a multiple of eight (or sixteen on 64-bit systems). If you need a block whose address is a multiple of a higher power of two than that, use Hmemalign@ or Hvalloc@. These functions are declared in H`stdlib.h'@.
With the GNU library, you can use Hfree@ to free the blocks that Hmemalign@ and Hvalloc@ return. That does not work in BSD, however--BSD does not provide any way to free such blocks.

AFunction:@ void * Dmemalign@ B(size_t Bboundary@, size_t Bsize@)
Â‰IDX227Š@�”˜The Hmemalign@ function allocates a block of Bsize@ bytes whose address is a multiple of Bboundary@. The Bboundary@ must be a power of two! The function Hmemalign@ works by allocating a somewhat larger block, and then returning an address within the block that is on the specified boundary.À

AFunction:@ void * Dvalloc@ B(size_t Bsize@)
Â‰IDX228Š@�”˜Using Hvalloc@ is like using Hmemalign@ and passing the page size as the value of the second argument. It is implemented like this: void *
valloc (size_t size)
{
return memalign (getpagesize (), size);
} À

ˆ‰SEC29ŠT�”›Malloc Tunable Parameters

@�”˜You can adjust some parameters for dynamic memory allocation with the Hmallopt@ function. This function is the general SVID/XPG interface, defined in H`malloc.h'@. ‰IDX229Š

A�”˜Function:@ int Dmallopt@ B(int Bparam@, int Bvalue@)
Â‰IDX230Š@�”˜When calling Hmallopt@, the Bparam@ argument specifies the parameter to be set, and Bvalue@ the new value to be set. Possible choices for Bparam@, as defined in H`malloc.h'@, are:
HM_TRIM_THRESHOLD
Ä@This is the minimum size (in bytes) of the top-most, releaseable chunk that will cause Hsbrk@ to be called with a negative argument in order to return memory to the system.
ÂHM_TOP_PAD
Ä@This parameter determines the amount of extra memory to obtain from the system when a call to Hsbrk@ is required. It also specifies the number of bytes to retain when shrinking the heap by calling Hsbrk@ with a negative argument. This provides the necessary hysteresis in heap size such that excessive amounts of system calls can be avoided.
ÂHM_MMAP_THRESHOLD
Ä@All chunks larger than this value are allocated outside the normal heap, using the Hmmap@ system call. This way it is guaranteed that the memory for these chunks can be returned to the system on Hfree@.
ÂHM_MMAP_MAX
Ä@The maximum number of chunks to allocate with Hmmap@. Setting this to zero disables all use of Hmmap@.Â
À

ˆ‰SEC30ŠT�”›Heap Consistency Checking

‰IDX231Š‰IDX232Š
@�”˜You can ask Hmalloc@ to check the consistency of dynamic storage by using the Hmcheck@ function. This function is a GNU extension, declared in H`malloc.h'@. ‰IDX233Š

A�”˜Function:@ int Dmcheck@ B(void (*Babortfn@) (enum mcheck_status Bstatus@))
Â‰IDX234Š@�”˜Calling Hmcheck@ tells Hmalloc@ to perform occasional consistency checks. These will catch things such as writing past the end of a block that was allocated with Hmalloc@.
The Babortfn@ argument is the function to call when an inconsistency is found. If you supply a null pointer, then Hmcheck@ uses a default function which prints a message and calls Habort@ (see section ‰ŠP�”›Aborting a Program@�”˜). The function you supply is called with one argument, which says what sort of inconsistency was detected; its type is described below.
It is too late to begin allocation checking once you have allocated anything with Hmalloc@. So Hmcheck@ does nothing in that case. The function returns H-1@ if you call it too late, and H0@ otherwise (when it is successful).
The easiest way to arrange to call Hmcheck@ early enough is to use the option H`-lmcheck'@ when you link your program; then you don't need to modify your program source at all.À

AFunction:@ enum mcheck_status Dmprobe@ B(void *Bpointer@)
Â‰IDX235Š@�”˜The Hmprobe@ function lets you explicitly check for inconsistencies in a particular allocated block. You must have already called Hmcheck@ at the beginning of the program, to do its occasional checks; calling Hmprobe@ requests an additional consistency check to be done at the time of the call.
The argument Bpointer@ must be a pointer returned by Hmalloc@ or Hrealloc@. Hmprobe@ returns a value that says what inconsistency, if any, was found. The values are described below.À

AData Type:@ Denum mcheck_status
Â‰IDX236Š@�”˜This enumerated type describes what kind of inconsistency was detected in an allocated block, if any. Here are the possible values:
HMCHECK_DISABLED
ÄHmcheck@ was not called before the first allocation. No consistency checking can be done.
ÂHMCHECK_OK
Ä@No inconsistency detected.
ÂHMCHECK_HEAD
Ä@The data immediately before the block was modified. This commonly happens when an array index or pointer is decremented too far.
ÂHMCHECK_TAIL
Ä@The data immediately after the block was modified. This commonly happens when an array index or pointer is incremented too far.
ÂHMCHECK_FREE
Ä@The block was already freed.Â
À

ˆ‰SEC31ŠT�”›Storage Allocation Hooks

‰IDX237Š
@�”˜The GNU C library lets you modify the behavior of Hmalloc@, Hrealloc@, and Hfree@ by specifying appropriate hook functions. You can use these hooks to help you debug programs that use dynamic storage allocation, for example.
The hook variables are declared in H`malloc.h'@. ‰IDX238Š

A�”˜Variable:@ D__malloc_hook
Â‰IDX239Š@�”˜The value of this variable is a pointer to function that Hmalloc@ uses whenever it is called. You should define this function to look like Hmalloc@; that is, like: void *Bfunction@ (size_t Bsize@) À

AVariable:@ D__realloc_hook
Â‰IDX240Š@�”˜The value of this variable is a pointer to function that Hrealloc@ uses whenever it is called. You should define this function to look like Hrealloc@; that is, like: void *Bfunction@ (void *Bptr@, size_t Bsize@) À

AVariable:@ D__free_hook
Â‰IDX241Š@�”˜The value of this variable is a pointer to function that Hfree@ uses whenever it is called. You should define this function to look like Hfree@; that is, like: void Bfunction@ (void *Bptr@) À

You must make sure that the function you install as a hook for one of these functions does not call that function recursively without restoring the old value of the hook first! Otherwise, your program will get stuck in an infinite recursion.
Here is an example showing how to use H__malloc_hook@ properly. It installs a function that prints out information every time Hmalloc@ is called. static void *(*old_malloc_hook) (size_t);
static void *
my_malloc_hook (size_t size)
{
void *result;
__malloc_hook = old_malloc_hook;
result = malloc (size);
/* Hprintf@ might call Hmalloc@, so protect it too. */
printf ("malloc (%u) returns %p\n", (unsigned int) size, result);
__malloc_hook = my_malloc_hook;
return result;
}

main ()
{
...
old_malloc_hook = __malloc_hook;
__malloc_hook = my_malloc_hook;
...
}
The Hmcheck@ function (see section ‰ŠP�”›Heap Consistency Checking@�”˜) works by installing such hooks.
ˆ‰SEC32ŠT�”›Statistics for Storage Allocation with \malloc

‰IDX242Š@�”˜You can get information about dynamic storage allocation by calling the Hmallinfo@ function. This function and its associated data type are declared in H`malloc.h'@; they are an extension of the standard SVID/XPG version. ‰IDX243Š

A�”˜Data Type:@ Dstruct mallinfo
Â‰IDX244Š@�”˜This structure type is used to return information about the dynamic storage allocator. It contains the following members:
Hint arena
Ä@This is the total size of memory allocated with Hsbrk@ by Hmalloc@, in bytes.
ÂHint ordblks
Ä@This is the number of chunks not in use. (The storage allocator internally gets chunks of memory from the operating system, and then carves them up to satisfy individual Hmalloc@ requests; see section ‰ŠP�”›Efficiency Considerations for Xmalloc@�”˜.)
ÂHint smblks
Ä@This field is unused.
ÂHint hblks
Ä@This is the total number of chunks allocated with Hmmap@.
ÂHint hblkhd
Ä@This is the total size of memory allocated with Hmmap@, in bytes.
ÂHint usmblks
Ä@This field is unused.
ÂHint fsmblks
Ä@This field is unused.
ÂHint uordblks
Ä@This is the total size of memory occupied by chunks handed out by Hmalloc@.
ÂHint fordblks
Ä@This is the total size of memory occupied by free (not in use) chunks.
ÂHint keepcost
Ä@This is the size of the top-most, releaseable chunk that normally borders the end of the heap (i.e. the "brk" of the process). Â
À

AFunction:@ struct mallinfo Dmallinfo@ B(void)
Â‰IDX245Š@�”˜This function returns information about the current dynamic memory usage in a structure of type Hstruct mallinfo@.À

ˆ‰SEC33ŠT�”›Summary of \mallocT-Related Functions

@�”˜Here is a summary of the functions that work with Hmalloc@:
Hvoid *malloc (size_t JsizeH)
Â@Allocate a block of Bsize@ bytes. See section ‰ŠP�”›Basic Storage Allocation@�”˜.
ÀHvoid free (void *JaddrH)
Â@Free a block previously allocated by Hmalloc@. See section ‰ŠP�”›Freeing Memory Allocated with Xmalloc@�”˜.
ÀHvoid *realloc (void *JaddrH, size_t JsizeH)
Â@Make a block previously allocated by Hmalloc@ larger or smaller, possibly by copying it to a new location. See section ‰ŠP�”›Changing the Size of a Block@�”˜.
ÀHvoid *calloc (size_t JcountH, size_t JeltsizeH)
Â@Allocate a block of Bcount@ * Beltsize@ bytes using Hmalloc@, and set its contents to zero. See section ‰ŠP�”›Allocating Cleared Space@�”˜.
ÀHvoid *valloc (size_t JsizeH)
Â@Allocate a block of Bsize@ bytes, starting on a page boundary. See section ‰ŠP�”›Allocating Aligned Memory Blocks@�”˜.
ÀHvoid *memalign (size_t JsizeH, size_t JboundaryH)
Â@Allocate a block of Bsize@ bytes, starting on an address that is a multiple of Bboundary@. See section ‰ŠP�”›Allocating Aligned Memory Blocks@�”˜.
ÀHint mallopt (int JparamH, int JvalueH)
Â@Adjust a tunable parameter. See section ‰ŠP�”›Malloc Tunable Parameters@�”˜
ÀHint mcheck (void (*JabortfnH) (void))
Â@Tell Hmalloc@ to perform occasional consistency checks on dynamically allocated memory, and to call Babortfn@ when an inconsistency is found. See section ‰ŠP�”›Heap Consistency Checking@�”˜.
ÀHvoid *(*__malloc_hook) (size_t JsizeH)
Â@A pointer to a function that Hmalloc@ uses whenever it is called.
ÀHvoid *(*__realloc_hook) (void *JptrH, size_t JsizeH)
Â@A pointer to a function that Hrealloc@ uses whenever it is called.
ÀHvoid (*__free_hook) (void *JptrH)
Â@A pointer to a function that Hfree@ uses whenever it is called.
ÀHstruct mallinfo mallinfo (void)
Â@Return information about the current dynamic memory usage. See section ‰ŠP�”›Statistics for Storage Allocation with Xmalloc@�”˜.À

ˆ‰SEC34Št�”›Obstacks

‰IDX246Š
@�”˜An Bobstack@ is a pool of memory containing a stack of objects. You can create any number of separate obstacks, and then allocate objects in specified obstacks. Within each obstack, the last object allocated must always be the first one freed, but distinct obstacks are independent of each other.
Aside from this one constraint of order of freeing, obstacks are totally general: an obstack can contain any number of objects of any size. They are implemented with macros, so allocation is usually very fast as long as the objects are usually small. And the only space overhead per object is the padding needed to start each object on a suitable boundary.
ˆ‰SEC35ŠT�”›Creating Obstacks

@�”˜The utilities for manipulating obstacks are declared in the header file H`obstack.h'@. ‰IDX247Š

A�”˜Data Type:@ Dstruct obstack
Â‰IDX248Š@�”˜An obstack is represented by a data structure of type Hstruct obstack@. This structure has a small fixed size; it records the status of the obstack and how to find the space in which objects are allocated. It does not contain any of the objects themselves. You should not try to access the contents of the structure directly; use only the functions described in this chapter.À

You can declare variables of type Hstruct obstack@ and use them as obstacks, or you can allocate obstacks dynamically like any other kind of object. Dynamic allocation of obstacks allows your program to have a variable number of different stacks. (You can even allocate an obstack structure in another obstack, but this is rarely useful.)
All the functions that work with obstacks require you to specify which obstack to use. You do this with a pointer of type Hstruct obstack *@. In the following, we often say "an obstack" when strictly speaking the object at hand is such a pointer.
The objects in the obstack are packed into large blocks called Bchunks@. The Hstruct obstack@ structure points to a chain of the chunks currently in use.
The obstack library obtains a new chunk whenever you allocate an object that won't fit in the previous chunk. Since the obstack library manages chunks automatically, you don't need to pay much attention to them, but you do need to supply a function which the obstack library should use to get a chunk. Usually you supply a function which uses Hmalloc@ directly or indirectly. You must also supply a function to free a chunk. These matters are described in the following section.
ˆ‰SEC36ŠT�”›Preparing for Using Obstacks

@�”˜Each source file in which you plan to use the obstack functions must include the header file H`obstack.h'@, like this: #include <obstack.h>
‰IDX249Š‰IDX250Š@�”˜Also, if the source file uses the macro Hobstack_init@, it must declare or define two functions or macros that will be called by the obstack library. One, Hobstack_chunk_alloc@, is used to allocate the chunks of memory into which objects are packed. The other, Hobstack_chunk_free@, is used to return chunks when the objects in them are freed. These macros should appear before any use of obstacks in the source file.
Usually these are defined to use Hmalloc@ via the intermediary Hxmalloc@ (see section ‰ŠP�”›Unconstrained Allocation@�”˜). This is done with the following pair of macro definitions: #define obstack_chunk_alloc xmalloc
#define obstack_chunk_free free
Though the storage you get using obstacks really comes from Hmalloc@, using obstacks is faster because Hmalloc@ is called less often, for larger blocks of memory. See section ‰ŠP�”›Obstack Chunks@�”˜, for full details.
At run time, before the program can use a Hstruct obstack@ object as an obstack, it must initialize the obstack by calling Hobstack_init@.

AFunction:@ int Dobstack_init@ B(struct obstack *Bobstack-ptr@)
Â‰IDX251Š@�”˜Initialize obstack Bobstack-ptr@ for allocation of objects. This function calls the obstack's Hobstack_chunk_alloc@ function. It returns 0 if Hobstack_chunk_alloc@ returns a null pointer, meaning that it is out of memory. Otherwise, it returns 1. If you supply an Hobstack_chunk_alloc@ function that calls Hexit@ (see section ‰ŠP�”›Program Termination@�”˜) or Hlongjmp@ (see section ‰ŠP�”›Non-Local Exits@�”˜) when out of memory, you can safely ignore the value that Hobstack_init@ returns.À

Here are two examples of how to allocate the space for an obstack and initialize it. First, an obstack that is a static variable: static struct obstack myobstack;
...
obstack_init (&myobstack);
Second, an obstack that is itself dynamically allocated: struct obstack *myobstack_ptr
= (struct obstack *) xmalloc (sizeof (struct obstack));

obstack_init (myobstack_ptr);
ˆ‰SEC37ŠT�”›Allocation in an Obstack

‰IDX252Š
@�”˜The most direct way to allocate an object in an obstack is with Hobstack_alloc@, which is invoked almost like Hmalloc@.

AFunction:@ void * Dobstack_alloc@ B(struct obstack *Bobstack-ptr@, int Bsize@)
Â‰IDX253Š@�”˜This allocates an uninitialized block of Bsize@ bytes in an obstack and returns its address. Here Bobstack-ptr@ specifies which obstack to allocate the block in; it is the address of the Hstruct obstack@ object which represents the obstack. Each obstack function or macro requires you to specify an Bobstack-ptr@ as the first argument.
This function calls the obstack's Hobstack_chunk_alloc@ function if it needs to allocate a new chunk of memory; it returns a null pointer if Hobstack_chunk_alloc@ returns one. In that case, it has not changed the amount of memory allocated in the obstack. If you supply an Hobstack_chunk_alloc@ function that calls Hexit@ (see section ‰ŠP�”›Program Termination@�”˜) or Hlongjmp@ (see section ‰ŠP�”›Non-Local Exits@�”˜) when out of memory, then Hobstack_alloc@ will never return a null pointer.À

For example, here is a function that allocates a copy of a string Bstr@ in a specific obstack, which is in the variable Hstring_obstack@: struct obstack string_obstack;

char *
copystring (char *string)
{
size_t len = strlen (string) + 1;
char *s = (char *) obstack_alloc (&string_obstack, len);
memcpy (s, string, len);
return s;
}
To allocate a block with specified contents, use the function Hobstack_copy@, declared like this:

AFunction:@ void * Dobstack_copy@ B(struct obstack *Bobstack-ptr@, void *Baddress@, int Bsize@)
Â‰IDX254Š@�”˜This allocates a block and initializes it by copying Bsize@ bytes of data starting at Baddress@. It can return a null pointer under the same conditions as Hobstack_alloc@.À

AFunction:@ void * Dobstack_copy0@ B(struct obstack *Bobstack-ptr@, void *Baddress@, int Bsize@)
Â‰IDX255Š@�”˜Like Hobstack_copy@, but appends an extra byte containing a null character. This extra byte is not counted in the argument Bsize@.À

The Hobstack_copy0@ function is convenient for copying a sequence of characters into an obstack as a null-terminated string. Here is an example of its use: char *
obstack_savestring (char *addr, int size)
{
return obstack_copy0 (&myobstack, addr, size);
}
Contrast this with the previous example of Hsavestring@ using Hmalloc@ (see section ‰ŠP�”›Basic Storage Allocation@�”˜).
ˆ‰SEC38ŠT�”›Freeing Objects in an Obstack

‰IDX256Š
@�”˜To free an object allocated in an obstack, use the function Hobstack_free@. Since the obstack is a stack of objects, freeing one object automatically frees all other objects allocated more recently in the same obstack.

AFunction:@ void Dobstack_free@ B(struct obstack *Bobstack-ptr@, void *Bobject@)
Â‰IDX257Š@�”˜If Bobject@ is a null pointer, everything allocated in the obstack is freed. Otherwise, Bobject@ must be the address of an object allocated in the obstack. Then Bobject@ is freed, along with everything allocated in Bobstack@ since Bobject@.À

Note that if Bobject@ is a null pointer, the result is an uninitialized obstack. To free all storage in an obstack but leave it valid for further allocation, call Hobstack_free@ with the address of the first object allocated on the obstack: obstack_free (obstack_ptr, first_object_allocated_ptr);
Recall that the objects in an obstack are grouped into chunks. When all the objects in a chunk become free, the obstack library automatically frees the chunk (see section ‰ŠP�”›Preparing for Using Obstacks@�”˜). Then other obstacks, or non-obstack allocation, can reuse the space of the chunk.
ˆ‰SEC39ŠT�”›Obstack Functions and Macros

‰IDX258Š
@�”˜The interfaces for using obstacks may be defined either as functions or as macros, depending on the compiler. The obstack facility works with all C compilers, including both ISO C and traditional C, but there are precautions you must take if you plan to use compilers other than GNU C.
If you are using an old-fashioned non-ISO C compiler, all the obstack "functions" are actually defined only as macros. You can call these macros like functions, but you cannot use them in any other way (for example, you cannot take their address).
Calling the macros requires a special precaution: namely, the first operand (the obstack pointer) may not contain any side effects, because it may be computed more than once. For example, if you write this: obstack_alloc (get_obstack (), 4);
you will find that Hget_obstack@ may be called several times. If you use H*obstack_list_ptr++@ as the obstack pointer argument, you will get very strange results since the incrementation may occur several times.
In ISO C, each function has both a macro definition and a function definition. The function definition is used if you take the address of the function without calling it. An ordinary call uses the macro definition by default, but you can request the function definition instead by writing the function name in parentheses, as shown here: char *x;
void *(*funcp) ();
/* Use the macro. */
x = (char *) obstack_alloc (obptr, size);
/* Call the function. */
x = (char *) (obstack_alloc) (obptr, size);
/* Take the address of the function. */
funcp = obstack_alloc;
This is the same situation that exists in ISO C for the standard library functions. See section ‰ŠP�”›Macro Definitions of Functions@�”˜.
DWarning:@ When you do use the macros, you must observe the precaution of avoiding side effects in the first operand, even in ISO C.
If you use the GNU C compiler, this precaution is not necessary, because various language extensions in GNU C permit defining the macros so as to compute each argument only once.
ˆ‰SEC40ŠT�”›Growing Objects

‰IDX259Š‰IDX260Š
@�”˜Because storage in obstack chunks is used sequentially, it is possible to build up an object step by step, adding one or more bytes at a time to the end of the object. With this technique, you do not need to know how much data you will put in the object until you come to the end of it. We call this the technique of Bgrowing objects@. The special functions for adding data to the growing object are described in this section.
You don't need to do anything special when you start to grow an object. Using one of the functions to add data to the object automatically starts it. However, it is necessary to say explicitly when the object is finished. This is done with the function Hobstack_finish@.
The actual address of the object thus built up is not known until the object is finished. Until then, it always remains possible that you will add so much data that the object must be copied into a new chunk.
While the obstack is in use for a growing object, you cannot use it for ordinary allocation of another object. If you try to do so, the space already added to the growing object will become part of the other object.

AFunction:@ void Dobstack_blank@ B(struct obstack *Bobstack-ptr@, int Bsize@)
Â‰IDX261Š@�”˜The most basic function for adding to a growing object is Hobstack_blank@, which adds space without initializing it.À

AFunction:@ void Dobstack_grow@ B(struct obstack *Bobstack-ptr@, void *Bdata@, int Bsize@)
Â‰IDX262Š@�”˜To add a block of initialized space, use Hobstack_grow@, which is the growing-object analogue of Hobstack_copy@. It adds Bsize@ bytes of data to the growing object, copying the contents from Bdata@.À

AFunction:@ void Dobstack_grow0@ B(struct obstack *Bobstack-ptr@, void *Bdata@, int Bsize@)
Â‰IDX263Š@�”˜This is the growing-object analogue of Hobstack_copy0@. It adds Bsize@ bytes copied from Bdata@, followed by an additional null character.À

AFunction:@ void Dobstack_1grow@ B(struct obstack *Bobstack-ptr@, char Bc@)
Â‰IDX264Š@�”˜To add one character at a time, use the function Hobstack_1grow@. It adds a single byte containing Bc@ to the growing object.À

AFunction:@ void Dobstack_ptr_grow@ B(struct obstack *Bobstack-ptr@, void *Bdata@)
Â‰IDX265Š@�”˜Adding the value of a pointer one can use the function Hobstack_ptr_grow@. It adds Hsizeof (void *)@ bytes containing the value of Bdata@.À

AFunction:@ void Dobstack_int_grow@ B(struct obstack *Bobstack-ptr@, int Bdata@)
Â‰IDX266Š@�”˜A single value of type Hint@ can be added by using the Hobstack_int_grow@ function. It adds Hsizeof (int)@ bytes to the growing object and initializes them with the value of Bdata@.À

AFunction:@ void * Dobstack_finish@ B(struct obstack *Bobstack-ptr@)
Â‰IDX267Š@�”˜When you are finished growing the object, use the function Hobstack_finish@ to close it off and return its final address.
Once you have finished the object, the obstack is available for ordinary allocation or for growing another object.
This function can return a null pointer under the same conditions as Hobstack_alloc@ (see section ‰ŠP�”›Allocation in an Obstack@�”˜).À

When you build an object by growing it, you will probably need to know afterward how long it became. You need not keep track of this as you grow the object, because you can find out the length from the obstack just before finishing the object with the function Hobstack_object_size@, declared as follows:

AFunction:@ int Dobstack_object_size@ B(struct obstack *Bobstack-ptr@)
Â‰IDX268Š@�”˜This function returns the current size of the growing object, in bytes. Remember to call this function Bbefore@ finishing the object. After it is finished, Hobstack_object_size@ will return zero.À

If you have started growing an object and wish to cancel it, you should finish it and then free it, like this: obstack_free (obstack_ptr, obstack_finish (obstack_ptr));
This has no effect if no object was growing.
‰IDX269Š@�”˜You can use Hobstack_blank@ with a negative size argument to make the current object smaller. Just don't try to shrink it beyond zero length--there's no telling what will happen if you do that.
ˆ‰SEC41ŠT�”›Extra Fast Growing Objects

‰IDX270Š
@�”˜The usual functions for growing objects incur overhead for checking whether there is room for the new growth in the current chunk. If you are frequently constructing objects in small steps of growth, this overhead can be significant.
You can reduce the overhead by using special "fast growth" functions that grow the object without checking. In order to have a robust program, you must do the checking yourself. If you do this checking in the simplest way each time you are about to add data to the object, you have not saved anything, because that is what the ordinary growth functions do. But if you can arrange to check less often, or check more efficiently, then you make the program faster.
The function Hobstack_room@ returns the amount of room available in the current chunk. It is declared as follows:

AFunction:@ int Dobstack_room@ B(struct obstack *Bobstack-ptr@)
Â‰IDX271Š@�”˜This returns the number of bytes that can be added safely to the current growing object (or to an object about to be started) in obstack Bobstack@ using the fast growth functions.À

While you know there is room, you can use these fast growth functions for adding data to a growing object:

AFunction:@ void Dobstack_1grow_fast@ B(struct obstack *Bobstack-ptr@, char Bc@)
Â‰IDX272Š@�”˜The function Hobstack_1grow_fast@ adds one byte containing the character Bc@ to the growing object in obstack Bobstack-ptr@.À

AFunction:@ void Dobstack_ptr_grow_fast@ B(struct obstack *Bobstack-ptr@, void *Bdata@)
Â‰IDX273Š@�”˜The function Hobstack_ptr_grow_fast@ adds Hsizeof (void *)@ bytes containing the value of Bdata@ to the growing object in obstack Bobstack-ptr@.À

AFunction:@ void Dobstack_int_grow_fast@ B(struct obstack *Bobstack-ptr@, int Bdata@)
Â‰IDX274Š@�”˜The function Hobstack_int_grow_fast@ adds Hsizeof (int)@ bytes containing the value of Bdata@ to the growing object in obstack Bobstack-ptr@.À

AFunction:@ void Dobstack_blank_fast@ B(struct obstack *Bobstack-ptr@, int Bsize@)
Â‰IDX275Š@�”˜The function Hobstack_blank_fast@ adds Bsize@ bytes to the growing object in obstack Bobstack-ptr@ without initializing them.À

When you check for space using Hobstack_room@ and there is not enough room for what you want to add, the fast growth functions are not safe. In this case, simply use the corresponding ordinary growth function instead. Very soon this will copy the object to a new chunk; then there will be lots of room available again.
So, each time you use an ordinary growth function, check afterward for sufficient space using Hobstack_room@. Once the object is copied to a new chunk, there will be plenty of space again, so the program will start using the fast growth functions again.
Here is an example: void
add_string (struct obstack *obstack, const char *ptr, int len)
{
while (len > 0)
{
int room = obstack_room (obstack);
if (room == 0)
{
/* Not enough room. Add one character slowly,
which may copy to a new chunk and make room. */
obstack_1grow (obstack, *ptr++);
len--;
}
else
{
if (room > len)
room = len;
/* Add fast as much as we have room for. */
len -= room;
while (room-- > 0)
obstack_1grow_fast (obstack, *ptr++);
}
}
}
ˆ‰SEC42ŠT�”›Status of an Obstack

‰IDX276Š‰IDX277Š
@�”˜Here are functions that provide information on the current status of allocation in an obstack. You can use them to learn about an object while still growing it.

AFunction:@ void * Dobstack_base@ B(struct obstack *Bobstack-ptr@)
Â‰IDX278Š@�”˜This function returns the tentative address of the beginning of the currently growing object in Bobstack-ptr@. If you finish the object immediately, it will have that address. If you make it larger first, it may outgrow the current chunk--then its address will change!
If no object is growing, this value says where the next object you allocate will start (once again assuming it fits in the current chunk).À

AFunction:@ void * Dobstack_next_free@ B(struct obstack *Bobstack-ptr@)
Â‰IDX279Š@�”˜This function returns the address of the first free byte in the current chunk of obstack Bobstack-ptr@. This is the end of the currently growing object. If no object is growing, Hobstack_next_free@ returns the same value as Hobstack_base@.À

AFunction:@ int Dobstack_object_size@ B(struct obstack *Bobstack-ptr@)
Â‰IDX280Š@�”˜This function returns the size in bytes of the currently growing object. This is equivalent to obstack_next_free (Bobstack-ptr@) - obstack_base (Bobstack-ptr@) À

ˆ‰SEC43ŠT�”›Alignment of Data in Obstacks

‰IDX281Š
@�”˜Each obstack has an Balignment boundary@; each object allocated in the obstack automatically starts on an address that is a multiple of the specified boundary. By default, this boundary is 4 bytes.
To access an obstack's alignment boundary, use the macro Hobstack_alignment_mask@, whose function prototype looks like this:

AMacro:@ int Dobstack_alignment_mask@ B(struct obstack *Bobstack-ptr@)
Â‰IDX282Š@�”˜The value is a bit mask; a bit that is 1 indicates that the corresponding bit in the address of an object should be 0. The mask value should be one less than a power of 2; the effect is that all object addresses are multiples of that power of 2. The default value of the mask is 3, so that addresses are multiples of 4. A mask value of 0 means an object can start on any multiple of 1 (that is, no alignment is required).
The expansion of the macro Hobstack_alignment_mask@ is an lvalue, so you can alter the mask by assignment. For example, this statement: obstack_alignment_mask (obstack_ptr) = 0;
has the effect of turning off alignment processing in the specified obstack.À

Note that a change in alignment mask does not take effect until Bafter@ the next time an object is allocated or finished in the obstack. If you are not growing an object, you can make the new alignment mask take effect immediately by calling Hobstack_finish@. This will finish a zero-length object and then do proper alignment for the next object.
ˆ‰SEC44ŠT�”›Obstack Chunks

‰IDX283Š‰IDX284Š
@�”˜Obstacks work by allocating space for themselves in large chunks, and then parceling out space in the chunks to satisfy your requests. Chunks are normally 4096 bytes long unless you specify a different chunk size. The chunk size includes 8 bytes of overhead that are not actually used for storing objects. Regardless of the specified size, longer chunks will be allocated when necessary for long objects.
The obstack library allocates chunks by calling the function Hobstack_chunk_alloc@, which you must define. When a chunk is no longer needed because you have freed all the objects in it, the obstack library frees the chunk by calling Hobstack_chunk_free@, which you must also define.
These two must be defined (as macros) or declared (as functions) in each source file that uses Hobstack_init@ (see section ‰ŠP�”›Creating Obstacks@�”˜). Most often they are defined as macros like this: #define obstack_chunk_alloc xmalloc
#define obstack_chunk_free free
Note that these are simple macros (no arguments). Macro definitions with arguments will not work! It is necessary that Hobstack_chunk_alloc@ or Hobstack_chunk_free@, alone, expand into a function name if it is not itself a function name.
If you allocate chunks with Hmalloc@, the chunk size should be a power of 2. The default chunk size, 4096, was chosen because it is long enough to satisfy many typical requests on the obstack yet short enough not to waste too much memory in the portion of the last chunk not yet used.

AMacro:@ int Dobstack_chunk_size@ B(struct obstack *Bobstack-ptr@)
Â‰IDX285Š@�”˜This returns the chunk size of the given obstack.À

Since this macro expands to an lvalue, you can specify a new chunk size by assigning it a new value. Doing so does not affect the chunks already allocated, but will change the size of chunks allocated for that particular obstack in the future. It is unlikely to be useful to make the chunk size smaller, but making it larger might improve efficiency if you are allocating many objects whose size is comparable to the chunk size. Here is how to do so cleanly: if (obstack_chunk_size (obstack_ptr) < Bnew-chunk-size@)
obstack_chunk_size (obstack_ptr) = Bnew-chunk-size@;
ˆ‰SEC45ŠT�”›Summary of Obstack Functions

@�”˜Here is a summary of all the functions associated with obstacks. Each takes the address of an obstack (Hstruct obstack *@) as its first argument.
Hvoid obstack_init (struct obstack *Jobstack-ptrH)
Â@Initialize use of an obstack. See section ‰ŠP�”›Creating Obstacks@�”˜.
ÀHvoid *obstack_alloc (struct obstack *Jobstack-ptrH, int JsizeH)
Â@Allocate an object of Bsize@ uninitialized bytes. See section ‰ŠP�”›Allocation in an Obstack@�”˜.
ÀHvoid *obstack_copy (struct obstack *Jobstack-ptrH, void *JaddressH, int JsizeH)
Â@Allocate an object of Bsize@ bytes, with contents copied from Baddress@. See section ‰ŠP�”›Allocation in an Obstack@�”˜.
ÀHvoid *obstack_copy0 (struct obstack *Jobstack-ptrH, void *JaddressH, int JsizeH)
Â@Allocate an object of Bsize@+1 bytes, with Bsize@ of them copied from Baddress@, followed by a null character at the end. See section ‰ŠP�”›Allocation in an Obstack@�”˜.
ÀHvoid obstack_free (struct obstack *Jobstack-ptrH, void *JobjectH)
Â@Free Bobject@ (and everything allocated in the specified obstack more recently than Bobject@). See section ‰ŠP�”›Freeing Objects in an Obstack@�”˜.
ÀHvoid obstack_blank (struct obstack *Jobstack-ptrH, int JsizeH)
Â@Add Bsize@ uninitialized bytes to a growing object. See section ‰ŠP�”›Growing Objects@�”˜.
ÀHvoid obstack_grow (struct obstack *Jobstack-ptrH, void *JaddressH, int JsizeH)
Â@Add Bsize@ bytes, copied from Baddress@, to a growing object. See section ‰ŠP�”›Growing Objects@�”˜.
ÀHvoid obstack_grow0 (struct obstack *Jobstack-ptrH, void *JaddressH, int JsizeH)
Â@Add Bsize@ bytes, copied from Baddress@, to a growing object, and then add another byte containing a null character. See section ‰ŠP�”›Growing Objects@�”˜.
ÀHvoid obstack_1grow (struct obstack *Jobstack-ptrH, char Jdata-charH)
Â@Add one byte containing Bdata-char@ to a growing object. See section ‰ŠP�”›Growing Objects@�”˜.
ÀHvoid *obstack_finish (struct obstack *Jobstack-ptrH)
Â@Finalize the object that is growing and return its permanent address. See section ‰ŠP�”›Growing Objects@�”˜.
ÀHint obstack_object_size (struct obstack *Jobstack-ptrH)
Â@Get the current size of the currently growing object. See section ‰ŠP�”›Growing Objects@�”˜.
ÀHvoid obstack_blank_fast (struct obstack *Jobstack-ptrH, int JsizeH)
Â@Add Bsize@ uninitialized bytes to a growing object without checking that there is enough room. See section ‰ŠP�”›Extra Fast Growing Objects@�”˜.
ÀHvoid obstack_1grow_fast (struct obstack *Jobstack-ptrH, char Jdata-charH)
Â@Add one byte containing Bdata-char@ to a growing object without checking that there is enough room. See section ‰ŠP�”›Extra Fast Growing Objects@�”˜.
ÀHint obstack_room (struct obstack *Jobstack-ptrH)
Â@Get the amount of room now available for growing the current object. See section ‰ŠP�”›Extra Fast Growing Objects@�”˜.
ÀHint obstack_alignment_mask (struct obstack *Jobstack-ptrH)
Â@The mask used for aligning the beginning of an object. This is an lvalue. See section ‰ŠP�”›Alignment of Data in Obstacks@�”˜.
ÀHint obstack_chunk_size (struct obstack *Jobstack-ptrH)
Â@The size for allocating chunks. This is an lvalue. See section ‰ŠP�”›Obstack Chunks@�”˜.
ÀHvoid *obstack_base (struct obstack *Jobstack-ptrH)
Â@Tentative starting address of the currently growing object. See section ‰ŠP�”›Status of an Obstack@�”˜.
ÀHvoid *obstack_next_free (struct obstack *Jobstack-ptrH)
Â@Address just after the end of the currently growing object. See section ‰ŠP�”›Status of an Obstack@�”˜.À

ˆ‰SEC46Št�”›Automatic Storage with Variable Size

‰IDX286Š‰IDX287Š‰IDX288Š
@�”˜The function Halloca@ supports a kind of half-dynamic allocation in which blocks are allocated dynamically but freed automatically.
Allocating a block with Halloca@ is an explicit action; you can allocate as many blocks as you wish, and compute the size at run time. But all the blocks are freed when you exit the function that Halloca@ was called from, just as if they were automatic variables declared in that function. There is no way to free the space explicitly.
The prototype for Halloca@ is in H`stdlib.h'@. This function is a BSD extension. ‰IDX289Š

A�”˜Function:@ void * Dalloca@ B(size_t Bsize@);
Â‰IDX290Š@�”˜The return value of Halloca@ is the address of a block of Bsize@ bytes of storage, allocated in the stack frame of the calling function.À

Do not use Halloca@ inside the arguments of a function call--you will get unpredictable results, because the stack space for the Halloca@ would appear on the stack in the middle of the space for the function arguments. An example of what to avoid is Hfoo (x, alloca (4), y)@.
ˆ‰SEC47Š\�”›allocaT Example

@�”˜As an example of use of Halloca@, here is a function that opens a file name made from concatenating two argument strings, and returns a file descriptor or minus one signifying failure: int
open2 (char *str1, char *str2, int flags, int mode)
{
char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
stpcpy (stpcpy (name, str1), str2);
return open (name, flags, mode);
}
Here is how you would get the same results with Hmalloc@ and Hfree@: int
open2 (char *str1, char *str2, int flags, int mode)
{
char *name = (char *) malloc (strlen (str1) + strlen (str2) + 1);
int desc;
if (name == 0)
fatal ("virtual memory exceeded");
stpcpy (stpcpy (name, str1), str2);
desc = open (name, flags, mode);
free (name);
return desc;
}
As you can see, it is simpler with Halloca@. But Halloca@ has other, more important advantages, and some disadvantages.
ˆ‰SEC48ŠT�”›Advantages of \alloca

@�”˜Here are the reasons why Halloca@ may be preferable to Hmalloc@: þÂ
• Using Halloca@ wastes very little space and is very fast. (It is open-coded by the GNU C compiler.)
• Since Halloca@ does not have separate pools for different sizes of block, space used for any size block can be reused for any other size. Halloca@ does not cause storage fragmentation.
• ‰IDX291Š@�”˜Nonlocal exits done with Hlongjmp@ (see section ‰ŠP�”›Non-Local Exits@�”˜) automatically free the space allocated with Halloca@ when they exit through the function that called Halloca@. This is the most important reason to use Halloca@. To illustrate this, suppose you have a function Hopen_or_report_error@ which returns a descriptor, like Hopen@, if it succeeds, but does not return to its caller if it fails. If the file cannot be opened, it prints an error message and jumps out to the command level of your program using Hlongjmp@. Let's change Hopen2@ (see section ‰ŠX�”›allocaP Example@�”˜) to use this subroutine: int
open2 (char *str1, char *str2, int flags, int mode)
{
char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
stpcpy (stpcpy (name, str1), str2);
return open_or_report_error (name, flags, mode);
} Because of the way Halloca@ works, the storage it allocates is freed even when an error occurs, with no special effort required. By contrast, the previous definition of Hopen2@ (which uses Hmalloc@ and Hfree@) would develop a storage leak if it were changed in this way. Even if you are willing to make more changes to fix it, there is no easy way to do so.Àð
ˆ‰SEC49ŠT�”›Disadvantages of \alloca

‰IDX292Š‰IDX293Š@�”˜These are the disadvantages of Halloca@ in comparison with Hmalloc@: þÂ
• If you try to allocate more storage than the machine can provide, you don't get a clean error message. Instead you get a fatal signal like the one you would get from an infinite recursion; probably a segmentation violation (see section ‰ŠP�”›Program Error Signals@�”˜).
• Some non-GNU systems fail to support Halloca@, so it is less portable. However, a slower emulation of Halloca@ written in C is available for use on systems with this deficiency.Àð
ˆ‰SEC50ŠT�”›GNU C Variable-Size Arrays

‰IDX294Š
@�”˜In GNU C, you can replace most uses of Halloca@ with an array of variable size. Here is how Hopen2@ would look then: int open2 (char *str1, char *str2, int flags, int mode)
{
char name[strlen (str1) + strlen (str2) + 1];
stpcpy (stpcpy (name, str1), str2);
return open (name, flags, mode);
}
But Halloca@ is not always equivalent to a variable-sized array, for several reasons: þÂ
• A variable size array's space is freed at the end of the scope of the name of the array. The space allocated with Halloca@ remains until the end of the function.
• It is possible to use Halloca@ within a loop, allocating an additional block on each iteration. This is impossible with variable-sized arrays.Àð
DNote:@ If you mix use of Halloca@ and variable-sized arrays within one function, exiting a scope in which a variable-sized array was declared frees all blocks allocated with Halloca@ during the execution of that scope.
ˆ‰SEC51Št�”›Relocating Allocator

‰IDX295Š@�”˜Any system of dynamic memory allocation has overhead: the amount of space it uses is more than the amount the program asks for. The Brelocating memory allocator@ achieves very low overhead by moving blocks in memory as necessary, on its own initiative.
ˆ‰SEC52ŠT�”›Concepts of Relocating Allocation

@�”˜When you allocate a block with Hmalloc@, the address of the block never changes unless you use Hrealloc@ to change its size. Thus, you can safely store the address in various places, temporarily or permanently, as you like. This is not safe when you use the relocating memory allocator, because any and all relocatable blocks can move whenever you allocate memory in any fashion. Even calling Hmalloc@ or Hrealloc@ can move the relocatable blocks.
‰IDX296Š@�”˜For each relocatable block, you must make a Bhandle@---a pointer object in memory, designated to store the address of that block. The relocating allocator knows where each block's handle is, and updates the address stored there whenever it moves the block, so that the handle always points to the block. Each time you access the contents of the block, you should fetch its address anew from the handle.
To call any of the relocating allocator functions from a signal handler is almost certainly incorrect, because the signal could happen at any time and relocate all the blocks. The only way to make this safe is to block the signal around any access to the contents of any relocatable block--not a convenient mode of operation. See section ‰ŠP�”›Signal Handling and Nonreentrant Functions@�”˜.
ˆ‰SEC53ŠT�”›Allocating and Freeing Relocatable Blocks

‰IDX297Š@�”˜In the descriptions below, Bhandleptr@ designates the address of the handle. All the functions are declared in H`malloc.h'@; all are GNU extensions.

AFunction:@ void * Dr_alloc@ B(void **Bhandleptr@, size_t Bsize@)
Â‰IDX298Š@�”˜This function allocates a relocatable block of size Bsize@. It stores the block's address in H*Jhandleptr@ and returns a non-null pointer to indicate success.
If Hr_alloc@ can't get the space needed, it stores a null pointer in H*Jhandleptr@, and returns a null pointer.À

AFunction:@ void Dr_alloc_free@ B(void **Bhandleptr@)
Â‰IDX299Š@�”˜This function is the way to free a relocatable block. It frees the block that H*Jhandleptr@ points to, and stores a null pointer in H*Jhandleptr@ to show it doesn't point to an allocated block any more.À

AFunction:@ void * Dr_re_alloc@ B(void **Bhandleptr@, size_t Bsize@)
Â‰IDX300Š@�”˜The function Hr_re_alloc@ adjusts the size of the block that H*Jhandleptr@ points to, making it Bsize@ bytes long. It stores the address of the resized block in H*Jhandleptr@ and returns a non-null pointer to indicate success.
If enough memory is not available, this function returns a null pointer and does not modify H*Jhandleptr@.À

Œ
Go to the ‰ŠP�”›first@�”˜, ‰ŠP�”›previous@�”˜, ‰ŠP�”›next@�”˜, ‰ŠP�”›last@�”˜ section, ‰ŠP�”›table of contents@�”˜.