concat_strings.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /**
  2. * @file concat_strings.h
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * This file is part of BadVPN.
  8. *
  9. * BadVPN is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2
  11. * as published by the Free Software Foundation.
  12. *
  13. * BadVPN is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. *
  22. * @section DESCRIPTION
  23. *
  24. * Function for concatenating strings.
  25. */
  26. #ifndef BADVPN_MISC_CONCAT_STRINGS_H
  27. #define BADVPN_MISC_CONCAT_STRINGS_H
  28. #include <string.h>
  29. #include <stdlib.h>
  30. #include <stdarg.h>
  31. #include <misc/debug.h>
  32. static char * concat_strings (int num, ...)
  33. {
  34. ASSERT(num >= 0)
  35. // calculate sum of lengths
  36. size_t sum = 0;
  37. va_list ap;
  38. va_start(ap, num);
  39. for (int i = 0; i < num; i++) {
  40. const char *str = va_arg(ap, const char *);
  41. size_t str_len = strlen(str);
  42. if (str_len > SIZE_MAX - 1 - sum) {
  43. return NULL;
  44. }
  45. sum += str_len;
  46. }
  47. va_end(ap);
  48. // allocate memory
  49. char *res_str = malloc(sum + 1);
  50. if (!res_str) {
  51. return NULL;
  52. }
  53. // copy strings
  54. sum = 0;
  55. va_start(ap, num);
  56. for (int i = 0; i < num; i++) {
  57. const char *str = va_arg(ap, const char *);
  58. size_t str_len = strlen(str);
  59. memcpy(res_str + sum, str, str_len);
  60. sum += str_len;
  61. }
  62. va_end(ap);
  63. // terminate
  64. res_str[sum] = '\0';
  65. return res_str;
  66. }
  67. #endif