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
3.9k views
in Technique[技术] by (71.8m points)

Array boundary in C

Previously when manipulating an array, I can go over the array bounds and I know that C is lenient. Now when I access a value that out of those boundaries, I get an error [-Warray-bounds] and it prevents me from diving into memory. Code:

#include <stdio.h>
int main(void)
{
    int arr[] = {1,2,3,4,5}; 
    printf("arr [0] is %d
", arr[0]); 
    printf("arr[10] is %d
", arr[10]);     
}

errors:

address.c:12:31: warning: array index 10 is past the end of the array (which contains 5 elements) [-Warray-bounds]
    printf("arr[10] is %d
", arr[10]);

Is that something new in a compiler, and if yes, how can I disable or enable it?


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

1 Reply

0 votes
by (71.8m points)

i can go over array bound

You "can" in the sense that it doesn't affect the well-formedness of the program and thus won't necessitate the compiler to issue a diagnostic message. Despite not being required to, if a compiler is able to detect the bug, then it is allowed to warn the programmer.

However if you do this, then the behaviour of the program will be undefined. That means that nothing about the behaviour of the program is guaranteed by the language. Undefined behaviour is detrimental to the usefulness of the program and its avoidance is extremely important.

As such: Do not access an array out of bounds! It's a bad thing to do.

Is that something new in a compiler

"New" is relative. At least version 4.7.1 of GCC is able to detect this, and it was released about 9 years ago. Clang 3.0.0 is likewise able to detect it and it was released about 10 years ago.

how can i disable or enable it?

Compilers generally provide options to enable and disable specific warnings. The warning message that you quoted states which warning option has enabled it.

[-Warray-bounds]

I recommend to not disable the warning, and to fix the bug when ever you see this warning.


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

...