quarta-feira, 25 de novembro de 2009

obstack looks cool

/*
* An obstack is a pool of memory
* containing a stack of objects
*/


#include <stdio.h>
#include <stdlib.h>
#include <obstack.h>


#define obstack_chunk_alloc xmalloc
#define obstack_chunk_free free
#define obstack_alloc_fail_handler  (fprintf (stderr, "Memory exhausted\n"); exit (EXIT_FAILURE);)

static struct obstack string_obstack;


void *
xmalloc (size_t size)
{
 register void *value = malloc (size);
 if (value == 0)
  return 0;
 
 return value;
}


char *
copystring (struct obstack *obstack_ptr, char *string)
{
 size_t len = strlen (string) + 1;
 char *s = (char *) obstack_alloc (obstack_ptr, len);
 memcpy (s, string, len);

 return s;
}


int 
main (void)
{
 char *str;

 obstack_init (&string_obstack);
 str = copystring (&string_obstack, "Hello World");
 printf ("%s\n", str);
 obstack_free (&string_obstack, str);
 return 0;
}

Nenhum comentário:

Postar um comentário