没有出界失误的 [英] No out of bounds error
本文介绍了没有出界失误的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须用C本code这需要在一堆字符
取值
#包括LT&;&stdio.h中GT;
#定义NEWLINE的'\\ n'
诠释的main()
{焦炭℃;
炭海峡[6];
INT I = 0;
而(((C =的getchar())!= NEWLINE))
{
海峡[I] = C;
++我;
的printf(%d个\\ N,I);
}返回0;
}
输入是:testtesttest
输出:
1
2
3
4
五
6
7
8
117
118
119
120
我的问题是:
-
为什么我没有得到一个出界(分段错误)例外,虽然我清楚地超过数组的容量?
-
为什么输出的数字一下子跳到非常大的数字?
我用C尝试这样做++,得到了相同的行为。任何人都可以请解释究竟是什么原因呢?
解决方案
- C不检查数组边界。如果您尝试取消引用指针指向的内存,你的程序没有权限访问时才会发生分段错误。只要将过去的数组到底是不太可能导致该行为。未定义行为就是这样 - 不确定的。它可能的显示的工作得很好,但你不应该依靠其安全性。
- 您的程序通过访问内存过去数组末尾导致不确定的行为。在这种情况下,它看起来像一个你的
海峡[i] = C
写会覆盖i的值
。 - C ++具有相同的规则为C确实在这种情况下。
I have this code in C which takes in bunch of char
s
#include<stdio.h>
# define NEWLINE '\n'
int main()
{
char c;
char str[6];
int i = 0;
while( ((c = getchar()) != NEWLINE))
{
str[i] = c;
++i;
printf("%d\n", i);
}
return 0;
}
Input is: testtesttest
Output: 1 2 3 4 5 6 7 8 117 118 119 120
My questions are:
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?
I tried this in C++ and got the same behavior. Could anyone please explain what is the reason for this?
解决方案
- 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屋!
查看全文