有条件地不修改常量数据是 C 中的未定义行为吗?

发布于 2025-01-10 20:20:58 字数 510 浏览 3 评论 0原文

我们有以下函数:

void foo(int flag, void *ptr) {
    if (flag)
        strcpy(ptr, "Hello World");
    code_that_does_not_attempt_to_modify_data_pointed_to_by(ptr);
}

以下内容是否有效:

const char *string_literal_ptr = "String literals are constant and may not be modified";
foo(0, string_literal_ptr);

我们将指向常量数据的指针传递给可能的函数(但不会,因为我们将 0 作为flag传递)修改指针指向的数据。考虑到程序控制在任何时候都不会达到修改常量数据的程度,这是否有效?或者仅仅存在指向 const 数据的非 const 指针就无效了?

We have the following function:

void foo(int flag, void *ptr) {
    if (flag)
        strcpy(ptr, "Hello World");
    code_that_does_not_attempt_to_modify_data_pointed_to_by(ptr);
}

Would the following be valid:

const char *string_literal_ptr = "String literals are constant and may not be modified";
foo(0, string_literal_ptr);

We are passing a pointer to constant data to a function that may (but will not because we passed 0 as flag) modify the data pointed to by the pointer. Is this valid, given that at no point the program control reaches the point of modifying the constant data? Or is the mere existence of a non const pointer that points to const data invalid somehow?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烟酉 2025-01-17 20:20:58

如果 flag 为 false,则 strcpy(ptr, "Hello World"); 不会被求值,并且 ptr 指向的数据字符串文字是无关紧要的。

如果未执行路径上的代码可能导致未定义的行为(由于其评估,而不是由于翻译过程中出现的某些语法约束),那么 C 将突破,因为对空指针的测试将不起作用:

if (p)
    Use pointer p to do something.

If flag is false then strcpy(ptr, "Hello World"); is not evaluated, and the fact that ptr points to the data of a string literal is irrelevant.

If code on unexecuted paths could cause undefined behavior (due to its evaluation, not due to some grammar constraint that arises during translation), then C would break throughly, as tests for null pointers would not work:

if (p)
    Use pointer p to do something.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文