malloc
just returns a pointer to some memory it allocated for you. It doesn't initialize that memory, zero it out, or anything like that. So what you're seeing when you print it out, is whatever junk was in there before.
Frankly, you're lucky you didn't open up a wormhole or something. C strings are nul-teminated, so when you pass that pointer around, you're technically not passing a string yet. When you pass it to a function that expects a string, all kinds of wackiness can ensue.
You should initialize the memory when you get it. The simplest initialization would be something like *C = '\0';
or C[0] = '\0';
, which turns the memory into a zero-length string. But you probably already have something to put there, or why would you be allocating memory in the first place? :P
Now that there's code, we can tweak it a bit to fix the issue...
int main() {
char A[200], B[200];
printf("Enter 2 words or sentences.\n");
// BTW: you should never, ever be using `gets`.
// use `fgets` and pass the size of your buffer to avoid overruns.
// note: it returns a null pointer if it fails...at which point you
// can't trust that A and B are strings, and should probably bail
if (!fgets(A, sizeof A, stdin)) return 1;
if (!fgets(B, sizeof B, stdin)) return 1;
// you don't want to call `strlen` over and over. save these lengths
size_t Alen = strlen(A);
size_t Blen = strlen(B);
// lop off the newlines
if (Alen && A[Alen - 1] == '\n') A[--Alen] = '\0';
if (Blen && B[Blen - 1] == '\n') B[--Blen] = '\0';
// You need enough space for both strings, plus a nul at the end.
// side note: you don't need to cast the pointer to a `char *`.
// also, sizeof(char) is 1 by definition, so no need to multiply by it.
char* C = malloc(Alen + Blen + 1);
if (!C) return 1;
// compare to the length variable instead
for (int i = 0; i < Alen; i++)
C[i] = A[i];
for (int i = 0; i < Blen; i++)
C[i + Alen] = B[i];
// important: nul-terminate the string
C[Alen + Blen] = '\0';
printf("%s", C);
// not strictly necessary at the end of main on a modern OS, but
// you should free what you malloc
free(C);
}