view common/strhelp.c @ 60:6acb1dae6185

Use strn functions and improve error handling. Even if we know the strings are NULL terminated we use length terminated string functions after a first strlen this makes it easier to assert that at one point we know the string is terminated and afterwards use the length of that.
author Andre Heinecke <aheinecke@intevation.de>
date Tue, 18 Mar 2014 11:28:02 +0000
parents 3f6378647371
children 355800cdefcc
line wrap: on
line source

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

static void
out_of_core(void)
{
    fputs("\nfatal: out of memory\n", stderr);
    exit(2);
}
void *
xmalloc( size_t n )
{
    void *p = malloc( n );
    if( !p )
        out_of_core();
    return p;
}

void *
xrealloc( void *a, size_t n )
{
    void *p = realloc( a, n );
    if( !p )
        out_of_core();
    return p;
}

char *
xstrndup( const char *string, const size_t len )
{
    char *p = xmalloc( len + 1 );
    memcpy( p, string, len );
    p[len] = '\0';
    return p;
}

unsigned int
strv_length (char **str_array)
{
    unsigned int i = 0;

    if (!str_array)
        return 0;

    while (str_array[i])
        ++i;

    return i;
}

void array_append_str(char ***pArray, const char *string, const size_t len)
{
    unsigned int old_len = 0;

    if (!*pArray) {
        *pArray = xmalloc(2 * sizeof(char*));
        (*pArray)[0] = xstrndup(string, len);
        (*pArray)[1] = NULL;
        return;
    }
    old_len = strv_length(*pArray);
    *pArray = xrealloc(*pArray, sizeof(char**) * (old_len + 2));

    (*pArray)[old_len] = xstrndup(string, len);
    (*pArray)[old_len + 1] = NULL;
}

void str_append_str(char **pDst, const char *appendage, const size_t len)
{
    if (!appendage)
        return;

    if (!*pDst) {
        *pDst = xstrndup(appendage, len);
    } else {
        size_t old_len = strlen(*pDst);
        size_t new_len = old_len + len + 1;
        *pDst = (char *)xrealloc(*pDst, sizeof(char) * (new_len));
        strncpy(*pDst + old_len, appendage, new_len);
        *pDst[new_len] = '\0';
    }
}

void
strfreev (char **str_array)
{
  if (str_array)
    {
      int i;

      for (i = 0; str_array[i] != NULL; i++)
        free (str_array[i]);

      free (str_array);
    }
}

http://wald.intevation.org/projects/trustbridge/