Posted By

mwb1100 on 07/03/12


Tagged

strcat String


Versions (?)

vstrconat


 / Published in: C
 

Concatenate a list of strings into a dynamically allocated string.

  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include <stdarg.h>
  4.  
  5. /*
  6.   vstrconcat() - return a newly allocated string that is the concatenation of
  7.   all the string passed in the variable length argument list.
  8.  
  9.   The argument list *must* be terminated with a NULL pointer.
  10.  
  11.   All other arguments must be char* to ASCIIZ strings.
  12.  
  13.   Thre return value is a pointer to a dynamically allocated
  14.   buffer that contains a null terminated string with
  15.   all the argument strings concatenated.
  16.  
  17.   The returned pointer must be freed with the standard free()
  18.   function.
  19.  
  20.  */
  21.  
  22. char* vstrconcat( char const* s1, ...)
  23. {
  24. size_t len = 0;
  25. char const* src = NULL;
  26. char* result = NULL;
  27. char* curpos = NULL;
  28.  
  29. va_list argp;
  30.  
  31. if (!s1) {
  32. return NULL; // maybe should return strdup("")?
  33. }
  34.  
  35. // determine the buffer size needed
  36.  
  37. src = s1;
  38. va_start(argp, s1);
  39.  
  40. while (src) {
  41. len += strlen(src); //TODO: protect against overflow
  42.  
  43. src = va_arg(argp, char const*);
  44. }
  45.  
  46. va_end(argp);
  47.  
  48. result = malloc(len + 1);
  49. if (!result) {
  50. return NULL;
  51. }
  52.  
  53. // copy the data
  54.  
  55. src = s1;
  56. va_start(argp, s1);
  57. curpos = result;
  58.  
  59. while (src) {
  60. size_t tmp = strlen(src);
  61.  
  62. memcpy(curpos, src, tmp);
  63. curpos += tmp;
  64.  
  65. src = va_arg(argp, char const*);
  66. }
  67. va_end(argp);
  68.  
  69. result[len] = '\0';
  70.  
  71. return result;
  72. }
  73.  
  74. /*
  75.   strconcat() - simple wrapper for the common of concatenating exactly
  76.   two strings into a dynamically allocated buffer
  77.  
  78.  */
  79. char* strconcat( char const* s1, char const* s2)
  80. {
  81. return vstrconcat( s1, s2, NULL);
  82. }

Report this snippet  

You need to login to post a comment.