Hello,
I'm just started to study malloc and realloc, so i just wrote this program to copy two string from user input and consenterate them. then ofcource print it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *str = malloc(3)
gets(str);
int sl = strlen(str);
str = realloc(str, sl);
strcpy(str, str);
char *str2 = malloc(2 * sl);
gets(str2);
str = strcat(str, str2);
printf("%s", str);
free(str);
free(str2);
return 0;
/*char *str = malloc(6);
strcpy(str, "get");
str = realloc(str, 10);
strcat(str, " buck bitch");
printf("%s", str);
free(str);*/
}
sometimes it works, sometimes it doesn't and sometimes it works and then crashes. what's wrong?