I'm new with dynamic memory allocation and I tried to write a simple program to concatenate 2 strings (one initialized and one read from stdin) using realloc for the first string. But I receive this error:
cygwin_exception::open_stackdumpfile: Dumping stack trace to malloc.exe.stackdump
The code breaks at realloc and I do not know why, could you please help?
Input: man alive.
Expected output: The most beloved man alive.
I have tried replacing strlen with a number but with no avail.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *str = "The most beloved";
char str2[20];
scanf("%[^\n]%*c", str2);
//printf("%s %s\n", str, str2);
str = (char *)realloc(str, strlen(str) + strlen(str2));
strcat(str, str2);
printf("%s\n", str);
free(str);
}