A strange div bug on Linux x86_64, (both dmd & ldc2): long -5000 / size_t 2 = 9223372036854773308

Tove tove at fransson.se
Thu Aug 13 19:24:11 UTC 2020


On Thursday, 13 August 2020 at 19:11:24 UTC, mw wrote:
> On Thursday, 13 August 2020 at 19:03:38 UTC, H. S. Teoh wrote:
>> On Thu, Aug 13, 2020 at 06:51:09PM +0000, mw via Digitalmars-d 
>> wrote:
>>> On Thursday, 13 August 2020 at 18:40:40 UTC, matheus wrote:
>>> > On Thursday, 13 August 2020 at 13:33:19 UTC, bachmeier 
>>> > wrote:
>>> > > ...
>>> > > The source of wrong behavior is vec.length having type 
>>> > > ulong. It
>>> > > would be very unusual for someone to even think about 
>>> > > that.
>>> > 
>>> > May I ask what type should it be?
>>> 
>>> Signed (size_t, the length of the machine's address space)
>> [...]
>>
>> size_t is unsigned, because the address space of a 64-bit 
>> machine is 2^64, but a signed value would only be able to 
>> address half of that space (2^63).
>
> Yes, I know that, that's why I put it in the brackets.
>
> But for practical purpose: half that space is large/good 
> enough, 2^63 = 9,223,372,036,854,775,808, you sure your machine 
> have that much memory installed? (very roughly, 9G of GB?)

One should always use unsigned whenever possible as it generates 
better code, many believe factor 2 is simply a shift, but not so 
on signed.

ssize_t fun_slow(ssize_t x)
{
     return x/2;
}

size_t fun_fast(size_t x)
{
     return x/2u;
}

fun_slow(long):                           # @fun_slow(long)
         mov     rax, rdi
         shr     rax, 63
         add     rax, rdi
         sar     rax
         ret
fun_fast(unsigned long):                           # 
@fun_fast(unsigned long)
         mov     rax, rdi
         shr     rax
         ret



More information about the Digitalmars-d mailing list