爲什麼gets如此危險?

這一段搬運自stackoverflow:
Why is gets() dangerous
The first internet worm (the Morris Internet Worm) escaped about 30 years ago (1988-11-02), and it used gets() and a buffer overflow as one of its methods of propagating from system to system. The basic problem is that the function doesn’t know how big the buffer is, so it continues reading until it finds a newline or encounters EOF, and may overflow the bounds of the buffer it was given.

You should forget you ever heard that gets() existed.

The C11 standard ISO/IEC 9899:2011 eliminated gets() as a standard function, which is A Good Thing™ (it was formally marked as ‘obsolescent’ and ‘deprecated’ in ISO/IEC 9899:1999/Cor.3:2007 — Technical Corrigendum 3 for C99, and then removed in C11). Sadly, it will remain in libraries for many years (meaning ‘decades’) for reasons of backwards compatibility.

以上:蠕蟲病毒就是來自與gets無限讀取的問題 由於gets不會判斷緩衝區有多大 所以會一直讀到EOF或者是’\n’ 這就有可能導致緩衝區溢出的問題

在C11(2011)標準中刪除了gets,但由於向下兼容導致這個函數一直存在庫裏
更安全的用法是用fgets指定讀取範圍 或是 用getline

另外:
有的時候寫題目用gets會導致WA 可能是由於

windows的換行符是\r\n,linux的換行符只有\n,在windows系統下用gets會吞掉每一行最後面的\r\n,但是linux下用gets只會吞掉最後一個\n
那麼問題來了,如果數據是在windows環境下構造的,換行符用的是\r\n,但是服務器是linux,管理員直接把windows下生成的數據沒經過任何處理就移動到了linux的服務器裏
, 那麼在oj的測評時,每一行的最後都會多一個\r,所以有時候會稀裏糊塗的wa
--------------------- 逍遙丶綦 來源:CSDN 原文:https://blog.csdn.net/qwb492859377/article/details/48323443
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!

所以如此不安全的gets還是少用爲妙…

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章