Mercurial > trustbridge
view common/strhelp.c @ 59:3f6378647371
Start work on cinst. Strhelp new helpers to work with C String
arrays and to have a terminating malloc / realloc
author | Andre Heinecke <aheinecke@intevation.de> |
---|---|
date | Tue, 18 Mar 2014 10:04:30 +0000 |
parents | |
children | 6acb1dae6185 |
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 * xstrdup( const char *string ) { void *p = xmalloc( strlen(string)+1 ); strcpy( p, string ); return p; } /** * strv_length: * @str_array: a %NULL-terminated array of strings * * Returns the length of the given %NULL-terminated * string array @str_array. * * Return value: length of @str_array. * */ unsigned int strv_length (char **str_array) { unsigned int i = 0; if (!str_array) return 0; while (str_array[i]) ++i; return i; } /* @brief append a string to a NULL terminated array of strings. * * @param[inout] array pointer to the NULL terminated list of string pointers. * @param[in] string pointer to the string to append to the list. * */ void array_append_str(char ***pArray, const char *string) { unsigned int old_len = strv_length(*pArray); *pArray = xrealloc(*pArray, sizeof(char**) * (old_len + 2)); *pArray[old_len] = xstrdup(string); *pArray[old_len + 1] = NULL; } /* @brief append a string to another string. * * @param[inout] pDst pointer to the string to be extended. * @param[in] appendage pointer to the string to append. * */ void str_append_str(char **pDst, const char *appendage) { size_t old_len = strlen(*pDst), added_len = strlen(appendage); size_t new_len = old_len + added_len + 1; if (!appendage) return; *pDst = (char *)xrealloc(*pDst, sizeof(char) * (new_len)); strcpy(*pDst + old_len, appendage); *pDst[new_len - 1] = '\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); } }