No modification of pointer values in safe functions?
H. S. Teoh
hsteoh at quickfur.ath.cx
Wed Jan 3 22:17:27 UTC 2018
On Wed, Jan 03, 2018 at 10:02:22PM +0000, Mark via Digitalmars-d-learn wrote:
> The documentation says the modification of pointer values is not
> allowed in safe functions. Yet the following compiles fine on dmd:
>
> void main() @safe
> {
> int* x = new int;
> int* y = new int;
> y=x;
> }
>
> Is this simply a compiler bug?
No, this use of pointers is perfectly safe. @safe does not mean "no
pointers". What is prohibited is:
- casting integers into pointers:
int* ptr = cast(int*) 0xdeadbeef; // not allowed in @safe
*ptr = 100; // oops, overwriting arbitrary memory
- arbitrary pointer arithmetic, like:
int x;
int* ptr = &x;
ptr++; // not allowed in @safe
*ptr = 100; // oops, overwriting arbitrary stack locations.
- overlapping a pointer with something else in a union, like:
union U {
int x;
int* ptr;
}
U u;
u.x = 12345;
*u.ptr = 100; // oops, overwriting arbitrary memory
// Note: @safe allows *reading* u.x after assigning a pointer to
// u.ptr, since you can't do anything unsafe with an int value;
// you just can't get a pointer value out of the union.
- casting pointers to pointers of a different type:
char ch;
char* p = &ch;
int* ip = cast(int*) p; // not allowed in @safe
*ip = 123; // oops, overwriting arbitrary stack locations
- making arbitrary slices from a pointer:
char[10] buf;
char* p = &buf[0];
auto q = p[0 .. 100]; // not allowed in @safe
q[99] = 100; // oops, overrunning end of buffer
There are probably other examples, but you get the point.
It's always OK to assign and dereference pointers in @safe code,
because, barring a compiler bug or unrelated @system code wreaking
havoc, it's not possible to get an invalid pointer value in @safe code.
(The caveat is that @safe code may call @trusted code, which in turn may
call @system code. So you really have to be sure that @trusted code is
actually trustworthy, otherwise you *might* get an invalid pointer
percolating into @safe code, and then all bets are off.)
T
--
Тише едешь, дальше будешь.
More information about the Digitalmars-d-learn
mailing list