d安全代码漏洞
原文
不能在@safe
代码中拥有指向栈内存
的全局变量
int** global;
immutable int imm;
static this() { imm = 42; }
void main() @safe
{
f(); /* `global` 现在指向栈.*/
stomp(); /* `*global` 指向`imm`. */
**global = 13; /* 覆盖 `imm`. */
assert(imm == 42);/*失败,意外更改(不变整)*/
}
void f() @safe
{
int* buf;
static struct Context0x0 { int** str; }
Context0x0[1] c = Context0x0(&buf);
global = c[0].str; /*应拒绝*/
}
void stomp() @safe
{
immutable int*[4] x = &imm;
}
更简单示例:
int** global;
struct S { int** str; }
void f() @safe
{
int* buf;
S[1] c = S(&buf);
global = c[0].str; /*应拒绝*/
}
应按域
推导c
.这样
S c = S(&buf);
声明,确实可推导
为域
.然后,下行就正确了.
所以,问题在推导
域时应查看
静态数组元素
,但目前没有.现在是错误
:c
域变量,赋值给非域
的全局.