在C89(也稱ANSI C)中省略了return語句未定義的行為?
考慮以下基本例子:
#include <stdio.h> int main(void) { printf("Hi there!\n"); }
它是否在C89中呼叫未定義的行為?我試圖從ofollow,noindex" target="_blank">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
or by the omission of any explicit definition of
. There is no difference in emphasis among these three: theyall describe “behavior that is undefined”.
和§5.1.2.2.3程式終止:
A return from the initial call to themain
function is equivalent to
calling theexit
function with the value returned by themain
function
as its argument. If themain
function executes a return that specifies
no value, the termination status returned to the host environment is
undefined.
我的理解是,後一條款並不涵蓋失蹤回報的情況,因為沒有從未援引的回執陳述,因此適用前一條款.
然而,隨之而來的閱讀意味著什麼不同,§6.6.6.4返回語句:
If areturn
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 themain
function executes a return that specifies
no value. the termination status returned to the host environment is
undefined.
“終止狀態未定義”一詞似乎不是UB,也沒有任何具體行為,但更像是C標準範圍之外,更像是“讓主機環境擔心,我們洗手這裡”.這是正確的內省嗎?
幾年前我實際調查了由此引起的問題.如果您有一些程式碼路徑與返回,而沒有其他程式碼路徑,它會變得更有趣.
由於@aruisdante在評論中推測,所展示的行為確實是“未定義”,但唯一未定義的部分是返回的值(它不像許多其他“未定義”的情況可能會導致程式崩潰).
這些日子實際上相當於一個安全風險,因為返回的’未定義’值通常是通常用於返回值(或者在某些實現中的堆疊)的CPU暫存器中發生的任何事情,理論上這可以用於洩漏敏感資料.
http://stackoverflow.com/questions/28203506/is-omitting-return-statement-undefined-behaviour-in-c89-aka-ansi-c