Comment #0 by snarwin+bugzilla — 2022-05-29T16:18:26Z
According to the language spec [1], the behavior of integer division is undefined when
* the denominator is 0, or
* the .min value of a signed integer type is divided by -1
However, both of these operations are allowed in @safe code. As of DMD 2.100.0, the following program compiles without errors:
---
int div(int n, int m) @safe { return n/m; }
void main() @safe
{
auto a = div(1, 0);
auto b = div(int.min, -1);
}
---
If integer division is to remain allowed in @safe code, the behavior of these divisions must be defined.
[1] https://dlang.org/spec/expression.html#division
Comment #1 by razvan.nitu1305 — 2022-08-10T10:05:00Z
Usually, Walter argues that @safe refers to memory safety. Yes, I know that in the spec it is stated that @safe code may not lead to undefined behavior, however, you can void initialize a variable (that is not a pointer) in safe code, then I don't see why you would not be able to divide by 0. These can lead to undefined behavior, but not necessarily to memory corruption.
Based on that, this bug report is invalid.
Comment #2 by snarwin+bugzilla — 2022-08-10T11:59:51Z
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
Comment #3 by robert.schadek — 2024-12-15T15:27:25Z