view common/strhelp.c @ 61:b8cd573bd3ac

Fix check for malloc result, found by cppcheck.
author Bernhard Reiter <bernhard@intevation.de>
date Tue, 18 Mar 2014 14:05:17 +0100
parents 6acb1dae6185
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/