1

This might sound pretty old school, but I'm still unable to figure out why the following program throws a segmentation fault. Any help would be great

#include <stdio.h>
pointer(char **x)
{
    printf ("Before %c",*x[0]);
    *x[0] = 'a';   // segmentation fault here!!
    printf ("After %c", *x[0]);
}
int main()
{
    char *x = "Hello";
    pointer(&x);
}
Django
  • 181
  • 2
  • 15
  • 6
    Look here, it's explained in the top answer: http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s-in-c – AntonH Aug 12 '14 at 20:08

2 Answers2

1

It's explained in the answer to this question.

TL;DR: the memory pointed to by char *x = "Hello"; is read only. Trying to write to it is illegal, and will result in a segmentation fault.

Community
  • 1
  • 1
AntonH
  • 6,359
  • 2
  • 30
  • 40
1

char *x = "Hello";

This declaration makes it read-only. Writing to it the way you tried is illegal.

See this for more information

Community
  • 1
  • 1
Asics
  • 858
  • 1
  • 11
  • 20