Why getting a "bus error" when playing with pointers?

Viewed 210

so I was playing with pointers because I didn't know what else to do and usually, I imagine what's going on under the hood after each instruction. But I recently came against an error that I don't really understand.

char *str = "test";
printf("%c", ++*str);

Output :

zsh: bus error

Expected output was a 'u' because as far as I know, it first dereference the first address of the variable 'str' wich is a 't' than increment it right ? Or am I missing something ?

Changing the code like so is not giving me any error but why ?

printf("%c", *++str);

Thank you !

1 Answers

You cannot modify the data in a string literal. What you expect will work if you do:

char buf[] = "test"; 
char *str = buf;
putchar(++*str);

because the content of buf is writeable.

Related