Fear of Compiler Magic
Timon Gehr
timon.gehr at gmx.ch
Sun Aug 4 17:41:52 UTC 2024
On 8/3/24 19:02, Walter Bright wrote:
> On 8/2/2024 2:29 AM, Dennis wrote:
>> You would think it's safe to transform this:
>> ```D
>> printf("x = %s\n", x);
>> printf("x = %s\n", x);
>> ```
>>
>> Into this:
>> ```D
>> const(char)* fmt = "x = %s\n";
>> printf(fmt, x);
>> printf(fmt, x);
>> ```
>>
>> But with magic printf format string rewrites, that transformation
>> turns correct code into memory corrupting code when x is an int.
>
> The transformation won't compile if the call is marked @safe, and won't
> compile with the various proposals to increase the default safety-ness.
> ...
The simple fact is that is that the magic treatment of the
string-literal leads to some trouble. I.e., this is a good illustration
about how magic instills fear.
> It is in the same box as:
>
> ```
> int[] array;
> x = array[5];
> ```
>
> and rewriting as:
>
> ```
> int[] array;
> x = *(array.ptr + 5);
> ```
Not at all. You just orthogonally removed the range check. This is a
completely unrelated case. Nothing surprising happens here.
More information about the Digitalmars-d
mailing list