對於scanf_s越界問題

在程序調試時,經常遇到0xc0000005越界問題。可能情況1,數據超出範圍,2,指針未初始化。

scanf_s()函數出現越界問題,可能就是由於scanf()與scanf_s()函數的區別不清楚。

scanf()在讀取數據時不檢查邊界,所以可能會造成內存訪問越界.

scanf_s提供更安全一些的機制 ,以防止溢出 , 變量取地址後要緊跟一個數字以表明最多讀取多少位字符。避免引用到不存在的元素,防止hacker利用原版的不安全性(漏洞)黑掉系統。所以在遇到越界問題時,要首先確保是否使用了scanf_s函數。如果有,一定要進行格式匹配。

scanf_s("%4c", &c, _countof(c)); // not null terminated



// crt_scanf_s.c
// This program uses the scanf_s and wscanf_s functions
// to read formatted input.
  
#include <stdio.h>
#include <stdlib.h>

int main( void )
{
   int      i,
            result;
   float    fp;
   char     c,
            s[80];
   wchar_t  wc,
            ws[80];

   result = scanf_s( "%d %f %c %C %s %S", &i, &fp, &c, 1,
                     &wc, 1, s, _countof(s), ws, _countof(ws) );
   printf( "The number of fields input is %d\n", result );
   printf( "The contents are: %d %f %c %C %s %S\n", i, fp, c,
           wc, s, ws);
   result = wscanf_s( L"%d %f %hc %lc %S %ls", &i, &fp, &c, 2,
                      &wc, 1, s, _countof(s), ws, _countof(ws) );
   wprintf( L"The number of fields input is %d\n", result );
   wprintf( L"The contents are: %d %f %C %c %hs %s\n", i, fp,
            c, wc, s, ws);
}

scanf_s的使用方法詳見:

https://technet.microsoft.com/zh-cn/library/w40768et(v=vs.110).aspx

 

發佈了7 篇原創文章 · 獲贊 16 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章