【问题标题】:Why call a __pure__ function but not use the answer?为什么调用 __pure__ 函数但不使用答案?
【发布时间】:2019-12-27 17:41:34
【问题描述】:

对于一个附带项目,我正在阅读一些 systemd 源代码。我发现__pure__ 函数endswithcg_get_root_path 内部的用法令人困惑。具体来说,为什么cg_get_root_path 函数中会存在变量e?它存储了endswith 的结果,但似乎从未真正使用过,而且endswith 函数没有我能看到的副作用。

char *endswith(const char *s, const char *postfix) _pure_;

int cg_get_root_path(char **path) {
        char *p, *e;
        int r;

        assert(path);

        r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
        if (r < 0)
                return r;

        e = endswith(p, "/" SPECIAL_INIT_SCOPE);
        if (!e)
                e = endswith(p, "/" SPECIAL_SYSTEM_SLICE); /* legacy */
        if (!e)
                e = endswith(p, "/system"); /* even more legacy */
        if (e)
                *e = 0;

        *path = p;
        return 0;
}

char* endswith(const char *s, const char *postfix) {
        size_t sl, pl;

        assert(s);
        assert(postfix);

        sl = strlen(s);
        pl = strlen(postfix);

        if (pl == 0)
                return (char*) s + sl;

        if (sl < pl)
                return NULL;

        if (memcmp(s + sl - pl, postfix, pl) != 0)
                return NULL;

        return (char*) s + sl - pl;
}

【问题讨论】:

    标签: c systemd


    【解决方案1】:

    最终有一行使用了e*e = 0 写入内存(写入endswith 已返回的地址)。

    【讨论】:

    • 天哪,你是对的。他们使用endswith 的返回值通过注入\0 来修剪字符串。没有遵循。谢谢!
    【解决方案2】:

    断言可能会引发错误,这是一个可能的副作用

    【讨论】:

      猜你喜欢
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-30
      • 1970-01-01
      • 2023-02-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多