bool passed by ref, safe or not ?
Steven Schveighoffer
schveiguy at gmail.com
Wed Jun 5 00:42:04 UTC 2024
On Tuesday, 4 June 2024 at 16:58:50 UTC, Basile B. wrote:
> question in the header, code in the body, execute on a X86 or
> X86_64 CPU
>
> ```d
> module test;
>
> void setIt(ref bool b) @safe
> {
> b = false;
> }
>
> void main(string[] args)
> {
> ushort a = 0b1111111111111111;
> bool* b = cast(bool*)&a;
> setIt(*b);
> assert(a == 0b1111111100000000); // what actually happens
> assert(a == 0b1111111111111110); // what would be safe
> }
> ```
>
> I understand that the notion of `bool` doesn't exist on X86,
> hence what will be used is rather an instruction that write on
> the lower 8 bits, but with a 7 bits corruption.
>
> Do I corrupt memory here or not ?
I don't think so. You passed an address to a bool, which uses 8
bits of space, even though the compiler treats it as a 1-bit
integer.
In order for your code to do what you expect, all bool writes
would have to be read/modify/write operations. I don't think
anyone would prefer this.
> Is that a safety violation ?
No, you are not writing to memory you don't have access to. An
address is pointing at a byte level, not a bit level.
-Steve
More information about the Digitalmars-d-learn
mailing list