gpt4 book ai didi

c - C 在编译和执行程序之间有区别吗?

转载 作者:太空狗 更新时间:2023-10-29 16:20:55 25 4
gpt4 key购买 nike

如果表达式的求值导致 C 中的未定义行为,并且该表达式总是在程序执行时求值(例如,如果它出现在 main 的开头),它是否符合 if一个实现在编译时拒绝它?编译/翻译程序和执行程序在 C 语言中有区别吗?

我知道有 C 的解释器。对于这种差异,C 标准如何处理它们?

Example (reading uninitialized local)

int main() {
int i;
return i;
}

运行它时,在执行的任何阶段(甚至在 main 被调用之前),程序都可以做一些有趣的事情。但是,当我们甚至没有尝试运行它时,也会发生一些有趣的事情吗?它会导致编译器本身发生缓冲区溢出吗?

最佳答案

来自 C11 草案:

3.4.3 undefined behavior

behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements

NOTE Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

终止翻译在(非规范性)注释中被提及为未定义行为的可能后果,因此显然不打算排除编译时影响。规范部分当然允许——它允许任何事情。因此,如果在编译期间检测到未定义的行为,符合标准的编译器可以终止翻译。

此外,$4 一致性:

If a ‘‘shall’’ or ‘‘shall not’’ requirement that appears outside of a constraint or runtime-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’’.

“翻译时间”和“执行时间”在规范定义和一致性描述中都没有区分。未定义行为的不同“种类”之间没有区别。

此外,Defect Report #109 ouah指出在 Can code that will never be executed invoke undefined behavior?在它的回应中有这个:

[...] If an expression whose evaluation would result in undefined behavior appears in a context where a constant expression is required, the containing program is not strictly conforming. Furthermore, if every possible execution of a given program would result in undefined behavior, the given program is not strictly conforming.

A conforming implementation must not fail to translate a strictly conforming program simply because some possible execution of that program would result in undefined behavior. [...]

这表明,如果编译器无法静态确定所有路径都会导致未定义的行为,那么它就不会导致翻译失败。

关于c - C 在编译和执行程序之间有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34557398/

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