2

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 !

5
  • char *str = "test"; is not correct in C++, so I assume this is C. Please only tag the language you are actually using Commented Aug 19, 2021 at 13:56
  • 5
    ++*str attempts to increment the read-only data in the string literal. Commented Aug 19, 2021 at 13:56
  • 2
    Don't write code like this: printf("%c", ++*str);. Break out your increment into a separate statement. As @WilliamPursell explains, the dereference occurs first, before the increment. Commented Aug 19, 2021 at 13:57
  • Try: char buf[] = "test"; char *str = buf; ... Commented Aug 19, 2021 at 13:57
  • String literals are not modifiable. You could use char str_data[] = "test"; char *str = str_data; or char *str = (char[]){ "test" }; instead, Commented Aug 19, 2021 at 13:59

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.