[英]Weird behaviour when returning FILE pointer from a C function
我正在查看一些舊的C代碼(下面列出),以便在新項目中重新使用它,我意識到我已經離開了最終的返回語句。 奇特的是,例程工作得很好並且確實返回了正確的文件指針。 任何人都可以向我解釋為什么會這樣嗎?
FILE* openforwrite(char *name, int binary)
{
//broken out from main to keep it tidy and allow multiple output files.
FILE *file;
//first see if it exists
file = fopen(name,"r");
if (file)
{ // it does, delete it
fclose(file);
if(remove(name)) bail("Output file already exists and cannot be deleted.");
}
//now lets re-create and open it for writing
if (binary)
file = fopen(name, "wb");
else
file = fopen(name, "w");
//check it actually opened
if (!file)
bail("Error opening output file.");
//and pass the pointer back
return file; // <-- I had omitted this line initially but the routine still worked
}
fopen
調用的返回值最終會將文件句柄放在通常用於返回值的寄存器中(例如, eax
)。 如果在函數退出之前沒有更改該寄存器值,則它仍可用於調用者。 例如,如果在fopen
和函數結束之前還有一個函數調用,那么它可能會覆蓋eax
寄存器並且肯定會失敗。 正如其他人所說,這是不明確的行為。 盡管如此,它最初是一個非常令人費解的情況(而且非常有趣)。
它只是碰巧工作。 編譯器使用堆棧將參數傳遞給函數,並接收它們的返回值。 它還在計算過程中將堆棧用於局部變量和臨時變量。 返回函數時,調用者查看堆棧中的特定位置以獲取返回值。 該值恰好包含文件指針值,因為這是函數計算的最后一個表達式。
在任何情況下,都不要認為這將再次以這種方式工作。
它可能會因各種原因而中斷,包括不同的編譯器版本,不同的優化,或者僅僅因為編譯器隨機決定教你一課。
問題是您調用了未定義的行為 。 它似乎可以工作,它可以崩潰,並且在緩沖區溢出的情況下,它可以刪除文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.