4 ms·
After thinking about it and reading the other comments, the for loop needs to be changed (k<15), because ++k sets k to 16 in the last step of the version in the
by dapperdrake 2y ago
After thinking about it and reading the other comments, the for loop needs to be changed (k<15), because ++k sets k to 16 in the last step of the version in the parent comment.
This one is nasty.
And it will still cause trouble close to arrays if size INT_MAX.
Fun times.
- nayuki 2y agoThe problem isn't ++k per se. The problem is the expression d[++k], which immediately reads d[16] before realizing that `k < 16` is false. Look at your sibling comments for explanations and corrections: https://news.ycombinator.com/item?id=43553392 https://news.ycombinator.com/item?id=43553392 , https://news.ycombinator.com/item?id=43553519 https://news.ycombinator.com/item?id=43553519 > And it will still cause trouble close to arrays if size INT_MAX. Fun fact, `for (int i = 0; i <= INT_MAX; i++) {}` is undefined behavior in C/C++ but a well-defined infinite loop in Java.
- dapperdrake 2y agoThe problem is checking for k<16 and incrementing k and then using k to access array d[16] afterwards. That's how it goes out if bounds. The condition is inadequate for ensuring that k stays in the bounds of array d[16]. It seems like k is "obviously" an array index for array d[16] here, but whatever. Not in a position to have that discussion right now. As for Java, (too lazy to look that up right now): That at least sounds like they enforce twos-complement representation for signed int values. C89 has UB here because ancient hardware also used ones-complement. And C89 wanted to be portable as a portable assembler. Well, if UB really makes anything portable. They didn't even go with platform-dependent a.k.a. implementation defined. Instead they specifically chose undefined behavior. The argument brought forward, at least today, is that C isn't supposed to be a portable assembler. Now which one is it supposed to be? Cannot have both at the same time.