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);
}
You declared a pointer to a string literal
char *str = "The most beloved";
String literals have static storage duration. So they may not be reallocated dynamically.
Thus this statement
str = (char *)realloc(str, strlen(str) + strlen(str2));
invokes undefined behavior.
Pay attention to that you need to reserve memory for the terminating zero character '\0'
of the result string.
What you need is the following
char *result = ( char * )malloc( strlen(str) + strlen(str2) + 1 );
strcpy( result, str );
strcat( result, str2 );
puts( result );
free( result );
Also it would be more safer to write
scanf("%19[^\n]", str2);