2

I am getting segmentation fault when running the below code. What could be the reason for this error? Please help

int main()
{
    char *str2 = "Hello";
    str2[3] = 'J';
    printf("%s\n",str2);
    return 0;
}
msc
  • 33,420
  • 29
  • 119
  • 214
Aaquil Ali
  • 59
  • 1
  • 5

3 Answers3

7

It is a undefined behaviour because you are trying to modify the content of a string literal. A string literal mainly stored in a read only location. so you do not modify it, otherwise it is invoked undefined behaviour.

C11 §6.4.5 String literals(Paragraph 7):

It is unspecified whether these arrays are distinct provided their elements have the appropriate values.If the program attempts to modify a string literal of either form, the behavior is undefined"

msc
  • 33,420
  • 29
  • 119
  • 214
  • 1
    `String literal stored in read only location`..well, the'res nothing mandatory, it's just UB to attempt any modifications. – Sourav Ghosh Nov 08 '17 at 07:04
3

You aren't allowed to modify a string constant, and in this case it's causing a runtime error. You can fix it by changing the declaration of str2 to:

char str2[] = "Hello";

This makes it an array, rather than a pointer to a string constant.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
2

You are not allowed to modify the memory pointed to by char* variables initialized with string literals. It is read-only.

Matt
  • 161
  • 9