Jump to content

Obstack

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Saif92 (talk | contribs) at 06:44, 30 October 2011 (Preparing for using Obstack). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

An obstack is a stack of objects (data items) which grows dynamically.

Obstack code typically provides C macros which take care of memory allocation and management for the user. Basically, obstacks are used as a form of memory management which can be more efficient and less difficult to implement than malloc/free in several situations.For example, say one needs to set up a stack for handling data items whose number grows for a while and then reach a final form; such a stack could be defined in obstack.h.

Creation

Preparing for using Obstack

For using obstack functions in any source file the user must include the header file obstack.h, like this:

          #include <obstack.h>

Also, if the source file uses the macro declaration for initialisation 'obstack_init', it must be declared or the two functions or macros that will be called by the obstack library should be defined. One, obstack_chunk_alloc, is used for allocation of chunks of memory into which objects are stored.

The other function, obstack_chunk_free is used to free the memory initially allocated.For avoiding any errors, these two functions should be included before any use of obstack in the source file.

Usually these are defined to use malloc via the intermediary xmalloc (see Unconstrained Allocation). This is done with the following pair of macro definitions:

    #define obstack_chunk_alloc xmalloc
    #define obstack_chunk_free free

Though the memory the user gets using obstacks really comes from malloc, using obstacks is faster because malloc is called less often, for larger blocks of memory. At run time, before the program can use a struct obstack object as an obstack, it must initialize the obstack by calling obstack_init.

    — Function: int obstack_init (struct obstack *obstack-ptr)

Initialize obstack obstack-ptr for allocation of objects. This function calls the obstack's obstack_chunk_alloc function. If allocation of memory fails, the function pointed to by obstack_alloc_failed_handler is called. The obstack_init function always returns 1 (Compatibility notice: Former versions of obstack returned 0 if allocation failed). 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);

— Variable: obstack_alloc_failed_handler

   The value of this variable is a pointer to a function that obstack uses when obstack_chunk_alloc fails to allocate memory. 

The default action is to print a message and abort. One should supply a function that either calls exit (see Program Termination) or longjump (see Non-Local Exits) and doesn't return.

   void my_obstack_alloc_failed (void)
   ...
   obstack_alloc_failed_handler = &my_obstack_alloc_failed;

Allocating objects

Freeing allocated objects

Once the object is allocated a new chunk of memory in obstack it must be freed after its use. To free an object allocated in an obstack, a function obstack_free is used. Since the obstack is a stack of objects, freeing one object automatically frees all other objects allocated more recently in the same obstack.

— Function:

 void obstack_free (struct obstack *obstack-ptr, void *object)

If object is a null pointer, everything allocated in the obstack is freed. Otherwise, object must be the address of an object allocated in the obstack. Then object is freed, along with everything allocated in obstack since object.

If object is a null pointer, the result is an uninitialized obstack. This will free all memory in an obstack but to leave it valid for further allocation, a function obstack_free with the address of the first object allocated on the obstack is called:

 obstack_free (obstack_ptr, first_object_allocated_ptr);

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 . Then other obstacks, or non-obstack allocation, can reuse the space of the chunk.

Example of allocating, storing, and deallocating objects in an obstack:

void test(int n) {

    struct obstack obst;

    obstack_init(&obst);

    /* Allocate memory for a string of length n -1 */
    char *str = obstack_alloc(&obst, n * sizeof(str[0]));

    /* Allocate an array for n nodes */
    node_t **nodes = obstack_alloc(&obst, n * sizeof(nodes[0]));

    /* Store the current mark of the obstack */
    void *mark = obstack_base (&obst);

    /* Allocate the nodes */
    for (i = 0; i < n; i++)
        nodes[i] = obstack_alloc(&obst, sizeof(node[0]));

    /* All the marks are gone */
    obstack_free(&obst, mark);

    /* Everything has gone */
    obstack_free(&obst, NULL);
}

Functions and macros

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.

In 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.

In ISO C, each function has both a macro definition and a function definition. The function definition is used if the address of the function without calling it is taken. 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)();

x = (char *) obstack_alloc(obptr, size); /* Use the macro. */
x = (char *) (obstack_alloc) (obptr, size); /* Call the function. */
funcp = obstack_alloc; /* Take the address of the function. */

This is the same situation that exists in ISO C for the standard library functions.

Alignment

Each obstack has an alignment 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 obstack_alignment_mask, whose function prototype looks like this:

— Macro:

 int obstack_alignment_mask (struct obstack *obstack-ptr)

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 obstack_alignment_mask is an lvalue, so the programmer can alter the mask by assignment. For example, the statement:

obstack_alignment_mask (obstack_ptr) = 0;


has the effect of turning off alignment processing in the specified obstack.

A change in alignment mask does not take effect until after the next time an object is allocated or finished in the obstack. If an object is not growing, then one can make the new alignment mask take effect immediately by calling obstack_finish. This will finish a zero-length object and then do proper alignment for the next object.

Obstack chunks

Obstacks work by allocating space for themselves in large chunks, and then parceling out space in the chunks to satisfy programmer's requests. Chunks are normally 4096 bytes long unless user 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 obstack_chunk_alloc, which the user must define. When a chunk is no longer needed because all the objects in it are freed, the obstack library frees the chunk by calling obstack_chunk_free, which should also be defined by the user.

These two must be defined as macros or declared as functions in each source file that uses obstack_init. Most often they are defined as macros like this:

#define obstack_chunk_alloc malloc
#define obstack_chunk_free free

These are simple macros (no arguments). It is necessary that obstack_chunk_alloc or obstack_chunk_free, alone, expand into a function name if it is not itself a function name.

If the user allocates chunks with malloc, 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.

— Macro:

 int obstack_chunk_size (struct obstack *obstack-ptr)

This returns the chunk size of the given obstack.

Since this macro expands to an lvalue, user can specify a new [[Chunking (computing) |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 user is allocating many objects whose size is comparable to the chunk size. Example of doing this is:

if (obstack_chunk_size (obstack_ptr) < new-chunk-size)
    obstack_chunk_size (obstack_ptr) = new-chunk-size;

References