没有越界错误 [英] No out of bounds error
本文介绍了没有越界错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 C 中有这段代码,它接受一堆 char
s
I have this code in C which takes in bunch of char
s
#include<stdio.h>
# define NEWLINE '
'
int main()
{
char c;
char str[6];
int i = 0;
while( ((c = getchar()) != NEWLINE))
{
str[i] = c;
++i;
printf("%d
", i);
}
return 0;
}
输入为:testtesttest
Input is: testtesttest
输出:12345678117118119120
Output: 1 2 3 4 5 6 7 8 117 118 119 120
我的问题是:
为什么我没有得到越界(分段错误)异常,尽管我明显超出了数组的容量?
Why don't I get an out of bounds (segmentation fault) exception although I clearly exceed the capacity of the array?
为什么输出中的数字突然跳到非常大的数字?
Why do the numbers in the output suddenly jump to very big numbers?
我在 C++ 中尝试了这个并得到了相同的行为.谁能解释一下这是什么原因?
I tried this in C++ and got the same behavior. Could anyone please explain what is the reason for this?
推荐答案
- C 不检查数组边界.仅当您尝试取消引用指向您的程序无权访问的内存的指针时,才会发生分段错误.简单地越过数组的末尾不太可能导致这种行为.未定义的行为就是 - 未定义.它可能看起来工作得很好,但你不应该依赖它的安全性.
- 您的程序通过访问数组末尾之后的内存来导致未定义的行为.在这种情况下,看起来您的
str[i] = c
写入之一覆盖了i
中的值. - 在这种情况下,C++ 具有与 C 相同的规则.
- C doesn't check array boundaries. A segmentation fault will only occur if you try to dereference a pointer to memory that your program doesn't have permission to access. Simply going past the end of an array is unlikely to cause that behaviour. Undefined behaviour is just that - undefined. It may appear to work just fine, but you shouldn't be relying on its safety.
- Your program causes undefined behaviour by accessing memory past the end of the array. In this case, it looks like one of your
str[i] = c
writes overwrites the value ini
. - C++ has the same rules as C does in this case.
这篇关于没有越界错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文