gpt4 book ai didi

c - 是否省略了 C89(又名 ANSI C)中的 return 语句未定义行为?

转载 作者:太空狗 更新时间:2023-10-29 16:34:22 26 4
gpt4 key购买 nike

考虑以下基本示例:

#include <stdio.h>

int main(void)
{
printf("Hi there!\n");
}

它会调用 C89 中的未定义行为吗?我试图从 this question 中获得一些意义,但大多数赞成的答案声称它是实现定义的,这里绝对没有 UB(Keith Thompson 的评论,这看起来很矛盾)。

规范在 §3.16 定义和约定中说:

If a “shall” or “shall not” requirement that appears outside of a constraint is violated. the behavior is undefined. Undefined behavior is otherwise indicated in this International Standard by the words “undefined behavior” or by the omission of any explicit definition of behavior. There is no difference in emphasis among these three: they all describe “behavior that is undefined”.

和 §5.1.2.2.3 程序终止:

A return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument. If the main function executes a return that specifies no value, the termination status returned to the host environment is undefined.

我的理解是后面的子条款不包括缺少返回的情况,因为 return 语句不是从不调用的,因此适用前面的子条款。

然而,进一步阅读表明有些不同,§6.6.6.4 return 语句:

If a return statement without an expression is executed, and the value of the function call is used by the caller, the behavior is undefined. Reaching the } that terminates a function is equivalent to executing a return statement without an expression.

好的,现在 5.1.2.2.3 子条款适用:

If the main function executes a return that specifies no value. the termination status returned to the host environment is undefined.

术语“终止状态未定义”似乎不是 UB,也不是任何特定行为,但更像是它超出了 C 标准的范围,更像是:“让宿主环境不用担心,我们从这里洗手”。是否正确解读?

最佳答案

几年前,我实际上调试了由此引起的问题。如果您有一些代码路径有返回值而其他代码路径没有返回值,它会变得更加有趣。

正如@aruisdante 在评论中推测的那样,表现出的行为确实是“未定义”的,但唯一未定义的部分是返回值(它不像许多其他可能导致程序崩溃的“未定义”情况)。

现在这实际上构成了安全风险,因为返回的“未定义”值通常是通常用于返回值的 CPU 寄存器中(或在某些实现中的堆栈中)的任何内容,理论上可用于泄露敏感数据。

关于c - 是否省略了 C89(又名 ANSI C)中的 return 语句未定义行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28203506/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com