I need to write a strcat in C. I tried below things:
char * c_strcat( char * str1, const char * str2)
{
char * ret = (char *) malloc(1 + strlen(str1)+ strlen(str2) );
if(ret!=NULL)
{
strcpy(ret, str1);
strcat(ret, str2);
if(str1 !=NULL) free str1; // If I comment this everything will be fine
return ret;
}
return NULL;
}
int main()
{
char * first = "Testone";
char *second = "appendedfromhere";
first = c_strcat(first,second);
if(second !=NULL) free(second);
// I want to store the result in the same variable
}
It crashed whenever I free the str1 memory in the c_strcat function. If I don't free then the memory allocated for the first will be leaked (if I understood properly).
How to store returned value to same variable (first)?