First, you shouldn't return reference to temporary
char con[lena+lenb];
(note that the garbage you get doesn't come from that since you print within the function)
Second, you don't allocate enough memory: should be (with first problem fixed):
char *con = malloc(lena+lenb+1);
then use strcpy/strcat anyway, it's faster, and your original code doesn't do anything useful (mixing chars with array of chars & the size of the arrays isn't known at this moment: that's the reason of the garbage you're getting):
strcpy(con,a);
strcat(con,b);
Or as some suggest that they're unsafe functions, and since we know the size of inputs we can write:
memcpy(con,a,lena);
memcpy(con+lena,b,lenb+1);
Also: the prototype of concat
is really wrong. It should be:
char *concat(const char *a, const char *b){
(as it returns a pointer on chars not a char. And the arguments should be constant pointers so you can use your function with any string)
and you're done (don't forget to free the string when you're done with it)
Fixed code (tested, surprisingly returns hello
, maybe because it compiles without errors with gcc -Wall -Wwrite-strings -Werror
. My advice: turn the warnings on and read them. You'll solve 80% of your problems that way):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *concat(const char *a, const char *b);
int main ()
{
char *con = concat("hel", "lo");
printf("%s\n",con);
return(0);
}
char *concat(const char *a, const char *b){
int lena = strlen(a);
int lenb = strlen(b);
char *con = malloc(lena+lenb+1);
// copy & concat (including string termination)
memcpy(con,a,lena);
memcpy(con+lena,b,lenb+1);
return con;
}