Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 views
in Technique[技术] by (71.8m points)

c - Why doesn't the compiler warns me about an obvious error?

So, I just studied the Arrays material and got a problem...
I got this following code:

int a[5]; 
int i;
for(i=0; i<=10; i++) {
    scanf("%d", &a[i]);
}

I declared on an array that its length is 5. image
Then, I ran a for loop from 0 to 10 that inserts numbers into a[i].
I used this table (which I created) to understand what happened during the execute time:
image
You see the red arrow? That's where the loop she be stopped, because they a[] cannot get more than 5 values into it. Which mean, that a[6] doesn't exist.
Even though, it keeps asking for numbers, and keeps saving them into the array.

One more thing, I'm currently using Dev C++ compiler.

Does anyone has an idea why is it happening?
Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

C doesn't have any standard on constraint on array index out of bound checking.

That means programs are free to violate the index rule. It is upto the programmers to check the array index constraint.

And, that will result in an undefined behaviour.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...