0

I have this in an exercise with pointers:

char *str = "Hello";
int count = 0;
int len = 5;
printf("%c\n", *(str + count));
printf("%c\n", *(str + len - count - 1));
*(str + count) = *(str + len - count - 1);

Both *(str + count) and *(str + len - count - 1) are valid values as the printfs attest (I get H and o). So why do I get a bus error when I run the above?

raheel
  • 1,407
  • 1
  • 15
  • 24

1 Answers1

3

str points to a string literal which resides in memory where it is undefined behaviour to write to. Many times the compiler will put these string literals into memory with permissions that do not include write-permissions. This is why you're crashing.

Change it to this:

char str[] = "Hello";

This will create an array on the stack and initialise it with the C-string "Hello"; since it resides on the stack, you can freely modify it.

Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
  • Any idea why is it a `bus error` and not just *segmentation fault*? – kaoD Feb 17 '12 at 02:56
  • @kaoD nope, no idea. Writing to string literals is Undefined Behaviour though, so absolutely anything could happen, including bus errors or the atmosphere exploding. – Seth Carnegie Feb 17 '12 at 02:56
  • Then I'm totally writing an infinite fork-and-crash loop... and watch the world burn! ;) – kaoD Feb 17 '12 at 03:00