0

So I have this super simple C code:

void reverse_string(char* string) {
  int length = strlen(string);
  for (int i = 0; i < length / 2; i++) {
    char temp = string[i];
    string[i] = string[length - 1 - i];
    string[length - 1 - i] = temp;
  }
}

int main() {
  // char* string = "hey this is a string"; <-- bus error
  char string[] = "hey this is a string";
  reverse_string(string);

  printf("%s\n", string);

  return 0;
}

and when I use the commented out line I get a bus error, but when I use the line below it everything's fine. Why is that?

Jack
  • 3
  • 3
  • String literals are immutable. – Paul Hankin Mar 06 '21 at 08:36
  • I would expect a segfault instead of a bus error though, aren't bus errors only for when you're trying to access memory that literally doesn't exist? – mediocrevegetable1 Mar 06 '21 at 08:37
  • Yeah I'm getting a bus error, not a segfault. – Jack Mar 06 '21 at 08:40
  • @Jack I just tried this code and I'm getting a segmentation fault. It really is undefined behavior, so I can't say why you're getting a bus error. In the future, to avoid getting these problems at runtime and instead get compile-time errors, I'd suggest you replace all `char*`s with `const char*`s. – mediocrevegetable1 Mar 06 '21 at 08:46
  • @mediocrevegetable1 Hm, odd. I'm using gcc on my macbook and it's telling me `zsh: bus error ./a.out`. But that sounds like good advice with `const char`. – Jack Mar 06 '21 at 08:50
  • @Jack never used a mac before, and I ran this on Linux. Perhaps it's something related to that? Can't really say anything for sure though. But yes, since string literals are immutable, you're asking for some weird error by trying to modify them. a `const char*` will allow the compiler to give you a proper error instead of confusing signal errors, which would save you a lot of time. – mediocrevegetable1 Mar 06 '21 at 08:54
  • 1
    @Jack since it is undefined behaviour, anything can happen - including nothing; so neither you nor mediocrevegetable should be surprised that you get different results on different platforms. In this case the OS has trapped it, it is nothing to do with the C language. – Clifford Mar 06 '21 at 14:06

0 Answers0