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;
}
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;
}
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"
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.
You are not allowed to modify the memory pointed to by char*
variables initialized with string literals. It is read-only.