对于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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章