2011-07-20 15 views
2

可能重複:
Why is the `gets' function is dangerous? Why should not be used?爲什麼fgets()在gcc(linux)中考慮以及使用它的替代方法是什麼?

我propting用戶輸入使用與fgets(),這將使用scanf()的區分整數來分析一個字符串,花車和chars.I希望一個可靠的程序,但我收到以下警告使用gcc:

在函數main': : warning: the得到'功能是危險的,不應該使用。

有人可以告訴我爲什麼它是危險的,它有什麼安全的選擇? 如果有人能告訴我fgets()的致命的嚴重性,那將是非常有用的。

+2

你可能意思是爲什麼'gets()'被認爲是危險的 - 而'fgets()'是另一種選擇:[爲什麼'gets'函數是危險的?爲什麼不應該使用?](http://stackoverflow.com/questions/1694036/why-is-the-gets-function-is-dangerous-why-should-not-be-used) – birryree

+0

好吧夥計,我的錯誤,對不起,我用我的程序gets()並寫了一個關於fgets()的問題 –

回答

4

你可能有點困惑。簡而言之:gets不好,fgets沒問題。

man頁解釋了爲什麼gets不應使用:

BUGS 
     Never use gets(). Because it is impossible to tell without knowing the 
     data in advance how many characters gets() will read, and because 
     gets() will continue to store characters past the end of the buffer, it 
     is extremely dangerous to use. It has been used to break computer 
     security. Use fgets() instead. 

fgets取緩衝區的大小作爲它的一個參數,如果正確地將使用,不存在這個問題。

該FAQ有entry with more details

+0

這個警告已經顯示fgets()也 –

+0

@ jatt.beas我懷疑這一點。 – cnicutar

+0

@ jatt.beas:我的'gcc'不會抱怨'fgets'(即使有'-Wall')。向我們展示代碼並告訴我們您的編譯器的版本。 – NPE

相關問題