Write concat() that returns a newly allocated string holding a followed by b. The caller frees it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *concat(const char *a, const char *b) { /* caller must free() the result */
size_t la = strlen(a), lb = strlen(b);
char *r = malloc(la + lb + 1);
if (r == NULL)
return NULL;
memcpy(r, a, la);
memcpy(r + la, b, lb + 1); /* + 1 copies the terminator */
return r;
}
int main(void) {
char *s = concat("Learn", "Frenzy");
if (s == NULL)
return 1;
printf("%s (%zu bytes allocated)\n", s, strlen(s) + 1);
free(s);
return 0;
}
LearnFrenzy (12 bytes allocated)
Measure both strings once, allocate exactly la + lb + 1 bytes, and copy with memcpy() – faster than strcpy + strcat, which would rescan the string.