Last active
January 20, 2017 08:40
-
-
Save alexandream/6e3f55d25cf532be8a1029e365f319c9 to your computer and use it in GitHub Desktop.
Join strings by a separator using varargs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdarg.h> | |
#include <string.h> | |
#include <stdlib.h> | |
static | |
size_t compute_joined_length(const char* separator, | |
const char* first, | |
va_list argp) { | |
size_t seplen = strlen(separator); | |
size_t length = strlen(first); | |
const char* next = va_arg(argp, const char*); | |
while (next != NULL) { | |
length += seplen + strlen(next); | |
next = va_arg(argp, const char*); | |
} | |
return length; | |
} | |
char* join_strings(const char* separator, const char* first, ...) { | |
size_t joined_length; | |
size_t separator_length = strlen(separator); | |
char* result = NULL; | |
va_list ap; | |
va_start(ap, first); | |
/* There's a one extra character to this length to account for the | |
* null character. */ | |
joined_length = compute_joined_length(separator, first, ap) + 1; | |
va_end(ap); | |
result = malloc(sizeof(char) * joined_length); | |
if (result != NULL) { | |
strcpy(result, first); | |
va_start(ap, first); | |
{ | |
size_t base_offset = strlen(first); | |
const char* next = va_arg(ap, const char*); | |
while (next != NULL) { | |
strcpy(result + base_offset, separator); | |
strcpy(result + base_offset + separator_length, next); | |
base_offset += strlen(next) + separator_length; | |
next = va_arg(ap, const char*); | |
} | |
} | |
va_end(ap); | |
result[joined_length - 1] = '\0'; | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
At line 35 you have one malloc and there is no free(result) after.
You functions allocs for every call a length of joinded_lenght bytes without freeing the memory.