[LCP]dynamic string

Joachim Bauernberger bj at gmx.net
Thu May 30 05:00:07 UTC 2002


Hi,
I would like to implement a string object (structure) for a library 
which I can grow dynamically. 
I intend to use this in a situation where I don't want to worry whether
src is gonna fit into dst (str(n)cpy() problem).
So far I have come up with the following however I am not really sure 
how efficient/useful this is. 

#define MCHUNK 1024

typedef struct str_t
{
  char *ss;             /* Buffer holding the string */
  size_t count;      /* number of chars in buffer */
  size_t size;         /* current space allocated  */
} str_t __attribute__ ((aligned));


str_t *
str_t_alloc (size_t chunk)
{
    void *res;

    res = xmalloc (sizeof (str_t));
    if (res) {
        str_t *mbuft_p = (str_t *) res;

        if (chunk) mbuft_p->ss = xcalloc(chunk,sizeof(char));
        else mbuft_p->ss = NULL;
        mbuft_p->count = 0;
        mbuft_p->size = 0;
    }
    return res;
}

/* deallocate structure */
void
str_t_free (str_t * p)
{
    if (p) {
        if (p->ss) {
            xfree (p->ss);
        }
        xfree (p);
    }
}

/*
 * Append n bytes of *src to *bufref->ss
 * If n exceeds the space left in *bufref we realloc
 * If that fails exit.
 * NULL terminate bufref->msg
 * This function does not modify src.
 */
inline str_t *
str_t_napp(str_t ** bufref, const char *src, size_t n)
{
    /* no data */
    if (!src || !*src) return *bufref;

    /* check for space left */
    while (n >= ((buf->size)-(buf->count)) ) {   
        char *tmp=NULL;
        if ((tmp =
realloc(*bufref->ss,(*bufref->size+MCHUNK)*sizeof(char)))) {
            *bufref->ss = tmp;
            *bufref->size += MCHUNK;
        } else {
              /* error */
        }
    }
    strncpy(*bufref->ss+(*bufref->count),src,n);
    *bufref->ss[*bufref->count+n+1] = '\0';
    *bufref->count += n;
    return *bufref;
}



/* A function can use the above the following way */

void foo(void)
{
     int i;
     str_t *string=NULL;

     string = str_t_alloc(MCHUNK);
    for (i=0;i<100000;++1) {
      str_t_napp(&string,"Hello World",strlen("Hello World"));
    }
    .......
    str_t_free(string);
 return;
}

I have implemented xmalloc to terminate the program with an error 
message in case malloc fails. Since I can't think of any situation 
where I would want to carry on in this case, can you?

Any thoughts on doing things differently?

Thanks & Best regards,
/joachim

PS:
Sorry for all that code but thought it'd be better than trying to 
describe what I want to achieve ....

--
http://www.cis.gsu.edu/~shong/oojokes/




More information about the linuxCprogramming mailing list