Does this implementation make any sense to you? I'm trying to write a function that will concatenate two strings and can be called as appendstr(&dest, "xyz");
I'm not sure at all if is a good practice what I'm doing here, reallocating the space for newptr
over origptr
and then free it and make it equal to newptr
.
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);
free(*origptr);
*origptr = newptr;
}
return newptr;
}
All I'm trying to do is to not change anything in *origptr
until I'm sure that there is no problem with the memory allocation and only then, do the concatenation.
Also, another concern is if I'm allocating exactly the amount of memory that I need.