程序没有崩溃缓冲区溢出时 [英] Program didn't crash when buffer overflow
问题描述
我想读通过键盘和存储在 BUF
的字符串。我设置了字符BUF [6]
阵,此阵最多可存储5个字符和 \\ 0
。
然后我键入 123 456 789
它包含11个字符和一个 \\ 0
,程序仍然可以运行,但如果我输入一个更长的字符串 123 456 789 123 456 789
它会崩溃在运行时。
这两个输入也出了 BUF
的范围内,但可以运行,其他的崩溃?
下面是我的code:
的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&string.h中GT;无效read_str();诠释主(){
read_str();
系统(暂停);
返回0;
}
无效read_str(){ 炭的buf [6] = {};
scanf函数(%[^ \\ n],BUF);
的printf(%d个\\ N的strlen(BUF));
的printf(%S \\ n,BUF);
}
这只是未定义行为到分配的内存边界之外写入。它现在可以工作,但它不能依靠工作。该 C99标准草稿附件 J.2
的未定义行为的说道:
这是数组下标超出范围,即使对象是显然访问
定标(如在左值前pression一个[1] [7]指定的声明INT
一个[4] [5])(6.5.6)。
块引用>请注意该节
3.4.3
的未定义行为的定义段期限的 2 的说(的重点煤矿的):
可能的不确定的行为从与联合国predictable结果完全无视形势的范围,在环境的记录方式的特点翻译或程序执行过程中的行为(有或没有发行的诊断消息),以终止翻译或执行(并出具诊断消息)。
块引用>I want to read a string from keyboard and store in
buf
. I set achar buf[6]
array , this array at most can store 5 characters and\0
.Then I type
123 456 789
it contain 11 characters and a\0
, the program still can run , but if I type a longer string123 456 789 123 456 789
it will crash at run time . these two inputs also out of the range ofbuf
, but one can run , the other crash?Here is my code:
#include <stdio.h> #include <stdlib.h> #include <string.h> void read_str(); int main(){ read_str(); system("pause"); return 0; } void read_str(){ char buf[6] = {}; scanf("%[^\n]",buf); printf("%d\n",strlen(buf)); printf("%s\n",buf); }
解决方案This is just undefined behavior to write outside the bounds of allocated memory. It may work now but it can not be relied on to work. The C99 draft standard in Annex
J.2
Undefined behavior says:An array subscript is out of range, even if an object is apparently accessible with the given subscript (as in the lvalue expression a[1][7] given the declaration int a[4][5]) (6.5.6).
Note that section
3.4.3
undefined behavior which defines the term in paragraph 2 says(emphasis mine):Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).
这篇关于程序没有崩溃缓冲区溢出时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!