0
int main()
{
        char *s="Hello";
        *s="World";
        printf("%s\n",s);
}

Why does the above program result in a segmentation fault?

jxh
  • 69,070
  • 8
  • 110
  • 193
user2076561
  • 139
  • 1
  • 2
  • 7

7 Answers7

4
int main()
{
    char *s="Hello"; // makes 's' point to a constant
    *s="World";      // modifies what 's' points to
    printf("%s\n",s);
}

The first line of code makes s point to a constant. The second line tries to modify what s points to. So you are trying to modify a constant, which you can't do because a constant is ... well ... constant.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
2

because *s is a char not a char*(string)

2
char *s="Hello";

declares a pointer to a string literal "Hello". This may exist in read-only memory so the line

*s="World";

is results in undefined behaviour. A crash is a valid (and useful) form of undefined behaviour.

Either of the following alternatives would work

const char* s = "Hello";
s="World";
printf("%s\n",s);

char s[16] = "Hello";
strcpy(s, "World";)
printf("%s\n",s);
simonc
  • 41,632
  • 12
  • 85
  • 103
  • Isn't the issue here that `*s` is a `char`, not a string? – verbose Aug 22 '13 at 19:50
  • 1
    That'd cause a warning/error at compile time. An segfault at run time will be coming from the attempt to write (the address of a different string literal) to the read-only location pointer to by `s`. – simonc Aug 22 '13 at 19:58
1

s points to static (global) memory when it is created. You cannot reassign to that memory at run-time, hence, the crash.

edtheprogrammerguy
  • 5,957
  • 6
  • 28
  • 47
1

*s is the first char of the string, so assigning string to character makes error.

If you want to assing string use s = "world"

int main()
{
    char *s="Hello";
    s="World";
    printf("%s\n",s);
}

now try it will work.

char *s="hello"; Here s is in readonly location. So we can assign another string, but cannot rewrite new string.

s = "hello"; //work
strcpy(s, "hello"); //segmentation fault
sujin
  • 2,813
  • 2
  • 21
  • 33
1

There are two problems here.

The statement

*s = "World";

dereferences s, which gives you the first character of the string "Hello", or 'H'. So you're trying to assign a pointer value (the address of the string "World") to a single char object (the first character of the "Hello" string literal).

But...

On some systems (such as yours, apparently), string literals are stored in a read-only data segment, and attempting to modify read-only memory will lead to a runtime error on some systems. Hence the crash.

To change s to point to the "World" string literal, simply drop the dereference:

s = "World";
John Bode
  • 119,563
  • 19
  • 122
  • 198
1

*s is the same as s[0]. s[0] has room to store a single character; in this case a 'W'.

There's not room to store the location of "World" in that character.

That's why you're getting a segmentation fault.

dcaswell
  • 3,137
  • 2
  • 26
  • 25