簡體   English   中英

為什么此代碼中存在緩沖區溢出?

[英]Why is there a buffer overflow in this code?

作為問題的一部分,我有一個結構,其中包含char isGoodchar filename[32]

有一個功能可以檢查文件中是否包含“ I'm a virus ”字符串,並返回isGood的值。

然后是以下代碼:

strncpy(currentItem.filename, argv[i], sizeof(currentItem.filename));
if (strlen(argv[i]) > sizeof(currentItem.filename)) {
    currentItem.filename[sizeof(currentItem.filename)] = '\0';
}

此代碼會導致錯誤,即使文件名中包含“ I'm a virus ”字符串,名稱大於32個字符的文件也將始終返回“ OK”。

為什么會這樣? 為什么更改currentItem.filename會更改currentItem.isGood的值? 它似乎與strncpy有關,因為我必須回答的下一個問題“結束用strncpy復制的字符串的正確方法是什么?”

這行代碼是您的緩沖區溢出:

currentItem.filename[sizeof(currentItem.filename)] = '\0';

sizeof(currentItem.filename)的值是緩沖區的長度。 如果在該索引處寫入,則將在數組末尾寫入一個點,從而導致溢出。

為了解決這個問題,寫

currentItem.filename[sizeof(currentItem.filename) - 1] = '\0';

更一般而言,您可能不希望使用strncpy ,而是要使用strlcpy ,這是大多數編譯器支持的編譯器擴展。 就像strncpy一樣,除了它總是放入一個空終止符。 這意味着您不必擔心添加自己的終結器。

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM