-3
int main()
{
char *p = "hello world!";
p[0] = 'H';
printf("%s",p);
getch();
}

I am new to C, can u guys tell me why is this program giving a segmentation fault?

  • Pointers declared this way point to a non-changeable part of memory. – Igor Pejic Aug 01 '14 at 18:01
  • http://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string Better duplicate target – Kevin L Aug 01 '14 at 18:01
  • You are modifying a string literal which is *undefined* in C. You could use an array instead: `char p[]="hello world!";` which will allow you to modify it. [More on this here](http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s-in-c). – P.P Aug 01 '14 at 18:04

1 Answers1

1

Because you try to set p[0] to 'H'. *p points to a string literal, which is stored in read-only memory.

Kevin L
  • 1,066
  • 3
  • 12
  • 21
  • 2
    String literals are not necessarily stored in read-only memory. It's simply undefined behaviour to modify them. – chris Aug 01 '14 at 18:57