-3

I want to change the contents of the char pointer after allocating dynamic memory, is it possible? If not, why? My program throws a run-time error.

#include <stdio.h>

int main()
{
    char * str = (char *) malloc (10 * sizeof(char));
    str = "Hello";
    str[2] = 'L'; // here the program throws run time error
    printf("%s", str);
    return 0;
}
Toby
  • 9,098
  • 14
  • 62
  • 127

1 Answers1

7

When pointing str = "Hello"; you didn't copy the "Hello" into the address pointed by str. Instead, you pointed str to string literal, and modifying it is UB -> run-time-error.

If you want to copy the content of a string Hello to str use strcpy.

As noted by @LethalProgrammer: using char[10] instead of char*would allow you modifying the content

CIsForCookies
  • 10,991
  • 7
  • 44
  • 96