What's wrong with this example with string literal?

  • A+
Category:Languages

I'm reading an answer from this site which says the following is undefined

char *fubar = "hello world"; *fubar++; // SQUARELY UNDEFINED BEHAVIOUR! 

but isn't that fubar++ is done first, which means moving the pointer to e, and *() is then done, which means extract the e out. I know this is supposed to be asked on chat (I'm a kind person) but no one is there so I ask here to attract notice.

 


The code shown is clearly not undefined behaviour, since *fubar++ is somewhat equal to char result; (result = *fubar, fubar++, result), i.e. it increments the pointer, and not the dereferenced value, and the result of the expression is the (dereferenced) value *fubar before the pointer got incremented. *fubar++ actually gives you the character value to which fubar originally points, but you simply make no use of this "result" and ignore it.

Note, however, that the following code does introduce undefined behaviour:

char *fubar = "hello world"; (*fubar)++; 

This is because this increments the value to which fubar points and thereby manipulates a string literal -> undefined behaviour.

When replacing the string literal with an character array, then everything is OK again:

int main() {      char test[] = "hello world";     char* fubar = test;     (*fubar)++;     printf("%s/n",fubar); } 

Output:

iello world 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: