| |
| Posted by Timon Gehr in reply to Walter Bright | PermalinkReply |
|
Timon Gehr
Posted in reply to Walter Bright
| On 18.02.22 09:05, Walter Bright wrote:
> On 2/17/2022 9:25 PM, Timon Gehr wrote:
>> Except perhaps for somewhat long arrays in a 32-bit program.
>
> Can't have everything.
> ...
Well, you I guess you *could* just use `long` instead of `ptrdiff_t`. (It seemed to me the entire point of this exercise was to do things in a way that's less error prone.)
> If you've got an array length longer than int.max,
Seems I likely won't have that (compiled with -m32):
```d
void main(){
import core.stdc.stdlib;
import std.stdio;
writeln(malloc(size_t(int.max)+1)); // null (int.max works)
auto a=new ubyte[](int.max); // out of memory error
}
```
> you're going to have trouble distinguishing a subtraction from a wraparound addition in any case.
Why? A wraparound addition is an addition where the result's sign differs from that of both operands. Seems simple enough.
If course, I can just sign-extend both operands so the total width precludes a wraparound addition. (E.g., just use `long`.)
> Dealing with that means one is simply going to have to pay attention to how integer 2-s complement arithmetic works on a computer.
> ...
Most of that is not too helpful as it's not exposed by the language. (At least in D, signed arithmetic actually has 2-s complement semantics, but the hardware has some features to make dealing with 2-s complement convenient that are not really exposed by the programming language.)
In any case, I can get it right, the scenario I had in mind is competent programmers having to spend time debugging a weird issue and then ultimately fix some library dependency that silently acquires funky behavior once the data gets a bit bigger than what's in the unit tests because the library authors blindly followed a `ptrdiff_t` recommendation they once saw in the forums. Unlikely to happen to me personally, as I currently see little reason to write 32-bit programs, even less 32-bit programs dealing with large arrays, but it seemed to me that "works" merited some minor qualification, as you kind of went out of your way to explicitly use the sometimes overly narrow `int` on 32-bit machines. ;)
Especially given that QA might mostly happen on 64 bit builds, that's probably quite risky in some cases.
|