As trying to concatenate two strings (char arrays), the code below returns the correct result via return but not the expected result through the arguments passed by reference (namely, char *dst in the StrAdd function).
Concerning the "after" results; printf prints the correct concatenated string for st. But the variable "s1" is supposed to contain the concatenated string as well. However, s1 prints something weird.
Can someone figure out what's wrong with it?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *StrAdd (char *dst, const char *src) {
/* add source string "src" at the end of destination string "dst"
i.e. concatenate
*/
size_t lenDst = strlen (dst);
size_t lenSrc = strlen (src);
size_t lenTot = lenDst + lenSrc + 1;
char *sTmp = (char *) malloc (lenTot);
memcpy (&sTmp [0], &dst [0], lenDst);
memcpy (&sTmp [lenDst], &src [0], lenSrc);
sTmp [lenTot - 1] = '\0';
free (dst);
dst = (char *) malloc (lenTot);
memcpy (&dst [0], &sTmp [0], lenTot);
free (sTmp);
return (dst);
}
int main () {
char *s1 = strdup ("Xxxxx");
char *s2 = strdup ("Yyyyy");
char *st = strdup ("Qqqqq");
printf ("s1 before: \"%s\"\n", s1);
printf ("s2 before: \"%s\"\n", s2);
printf ("st before: \"%s\"\n", st);
printf ("\n");
st = StrAdd (s1, s2);
printf ("s1 after : \"%s\"\n", s1); // weird???
printf ("s2 after : \"%s\"\n", s2); // ok
printf ("st after : \"%s\"\n", st); // ok
printf ("\n");
return (0);
}