This should be enough. It's just your code without the free()
void *appendstr(char **origptr, const char *strdata)
{
size_t len1 = strlen(*origptr);
size_t len2 = strlen(strdata);
char *newptr = realloc(*origptr, len1 + len2 + 1);
if (newptr != NULL)
{
memcpy(newptr + len1, strdata, len2 + 1);
*origptr = newptr;
}
return newptr;
}
Returns NULL
if it couldn't concatenate the strings, and *origptr
is not changed. Otherwise, it returns the (possibly new) allocated pointer with data concatenated. *origptr
then will have the same value as the returned value.
memcpy()
instead of strcat()
because strcat()
needs to know where the string ends by calling strlen()
internally (or doing its own version of strlen()
). As anyway you call strlen()
because you need the length of the string to calculate the amount of memory to allocate, you can use memcpy()
to directly copy the second string right after the first one, skipping an implicit second call to strlen()
if were using strcat()
.