在程序调试时,经常遇到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
本文介绍了如何解决程序调试中常见的0xc0000005越界问题,主要讨论了使用scanf_s()函数时可能出现的问题及正确的使用方法。
990

被折叠的 条评论
为什么被折叠?



