[Issue 23147] Integer division may cause undefined behavior in @safe code

d-bugmail at puremagic.com d-bugmail at puremagic.com
Wed Aug 10 11:59:51 UTC 2022


https://issues.dlang.org/show_bug.cgi?id=23147

--- Comment #2 from Paul Backus <snarwin+bugzilla at gmail.com> ---
Undefined behavior means that all bets are off and literally anything can
happen, including memory corruption.

Note that LDC at least optimizes code under the assumption that division by
zero never happens, so this is not a theoretical concern. This is demonstrated
by the following program, compiled with LDC 1.30.0 using the -O option:

---
bool example(int a, int b)
{
    if (a / b)
    {
        return b == 0;
    }
    else return false;
}

void main()
{
    import std.stdio;

    int a = 1, b = 0;

    writeln(a / b); // nonzero
    writeln(example(a, b)); // false
}
---

Godbolt link: https://godbolt.org/z/WPfx796Y9

--


More information about the Digitalmars-d-bugs mailing list