有条件地不修改常量数据是 C 中的未定义行为吗?
我们有以下函数:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果
flag
为 false,则strcpy(ptr, "Hello World");
不会被求值,并且ptr
指向的数据字符串文字是无关紧要的。如果未执行路径上的代码可能导致未定义的行为(由于其评估,而不是由于翻译过程中出现的某些语法约束),那么 C 将突破,因为对空指针的测试将不起作用:
If
flag
is false thenstrcpy(ptr, "Hello World");
is not evaluated, and the fact thatptr
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: