I'm doing a client-server project in linux and I need to concatenate some strings.
I tried my code on visual studio in windows and it works fine, but it linux it gives me some garbage. I've got this function:
char* concat(char s1[], char s2[])
{
int tam = 0;
tam = strlen(s1);
tam += strlen(s2);
char *resultado = malloc(sizeof(char) * tam) ;
strcpy(resultado, s1);
strcat(resultado, s2);
return resultado;
}
I read that the problem is the missing of '\0'
and I've done that:
char* concat(char s1[], char s2[])
{
int tam = 0;
tam = strlen(s1);
tam += strlen(s2);
char *resultado = malloc(sizeof(char) * tam) ;
resultado[tam+1] = '\0';
strcpy(resultado, s1);
strcat(resultado, s2);
return resultado;
}
The first 4 times that I called the function it works (the garbage disappeared), but then it gives me `malloc(): memory corruption
Anyone can help me?