3

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);
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • You can only use `realloc` on memory previously allocated by `malloc`. Not on other memory which wasn't allocated on the heap. – Lundin Apr 06 '21 at 10:18

2 Answers2

1

You are assigning a pointer to str which was not allocated using malloc. You may pass pointers to free or realloc only if they have been allocated using malloc.

Proper usage of realloc()

You could do

str = strdup("mystring");

Also here you need to account for the \0 at the end, so it should be:

str = (char *)realloc(str, strlen(str) + strlen(str2)+1);
Devolus
  • 21,661
  • 13
  • 66
  • 113
1

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);
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335