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域变量,赋值给非域的全局.

posted @   zjh6  阅读(15)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示