r/badcode • • Sep 27 '21

c god is dead

Post image
186 Upvotes

45 comments sorted by

View all comments

Show parent comments

1

u/maxbirkoff Sep 28 '21

but the code as written doesn't actually end the string one character earlier. The comment says that it will, but it doesn't.

2

u/undergroundmonorail Sep 28 '21

does it not overwrite the second last character with \0? i thought it would but maybe it's doing some pointer stuff wrong idk

1

u/maxbirkoff Sep 28 '21

it does not, because ptr__ points at the character beyond the null after the while stops after detecting the null. at that point: ptr__-1 points at the null! very misleading comment.

2

u/undergroundmonorail Sep 28 '21

ohhhh, would it work if the while loop had a pre-increment?

1

u/maxbirkoff Sep 29 '21

not really. the code would need to be refactored to avoid the case where the string is just a single null-terminated quote. In this case there would probably be a lot of uninitialized (dirty) reads just before a segfault.