2

I still not understand why it say me "Segmentation fault" at line 7 (when I try to access at one character with this command '*s'), can someone help me please?

This is the entire simple program:

#include <stdio.h>

void f(char* s, char c) {

  s++;
  s++;
  *s = c;
}

int main() {

  char* s = "hello!";
  f(s, 'd');
  printf("%s\n", s);
  return 0;
}

Thanks in advance.

  • What's the purpose of the code? – Sourav Ghosh Oct 27 '17 at 08:37
  • 1
    You should know what your doing at line 7 `*s = c`; ? char *s is string literal. You can't modify it. – danglingpointer Oct 27 '17 at 08:40
  • BTW, this is a FAQ and I'm not surprised, because a string literal is assignable to a `char *`. Anyone knows a rationale behind this? It would IMHO make more sense to allow assignment only to `const char*` (but of course, still allow a string literal as a `char` array initializer)... –  Oct 27 '17 at 08:45
  • 1
    If you initialize `s` this way it is a string literal. So the string is stored in read-only location and that memory address is returned to s . So when you try to write to the read-only location you see undefined behavior and might see a crash. – Phil Fighter Oct 27 '17 at 11:18

0 Answers0