C language array subscript out of bounds causes array overflow

array overflow

Arrays in C language are static and cannot be automatically expanded. Therefore, when the subscript is less than zero or greater than or equal to the defined array length, an out-of-bounds will occur and the memory space outside the defined array will be accessed.

There are two types of out-of-bounds forms for arrays: Off Normal Lower (subscript less than zero); upper limit out-of-bounds (Off Normal Upper, subscript greater than or equal to the defined array length) .


spillover consequences

In order to improve the operating efficiency and ensure the flexibility of the operation, the C language does not check the out-of-bounds behavior of the array. Therefore, even if the array is out of bounds, it can be compiled normally, and the problem may be exposed only during runtime.

But in fact, the consequences of array out of bounds may be very serious, such as sometimes "garbled characters", that is, inexplicable data, because when an array out of bounds occurs, we have permission to use the memory, but the program does not run as expected ; In severe cases, the program crashes, because we do not have permission to use the memory, or the memory has not been allocated.

/*该代码能正常编译,但程序发生上限越界(Off Normal Upper,下标大于等于所定义的数组长度)*/
/*因为正确的下标应该是从0开始,到9结束,但程序中产生了一个array[10]的错误,即数组下标越界*/

#include <stdio.h>
#define ARR_SIZ 10
int main()
{
    
    
   int i;
   int array[ARR_SIZ];
   for (i = 0; i <= ARR_SIZ; i++)
   {
    
    
       array[i] = 0;
       printf("%d\n", i);
   }
}

Note: GCC, LLVM/Clang, and lower versions of VS (such as VS2010) will only give a warning if an array overflow is found, and will not report an error. However, higher versions of VS (such as VS2015, VS2017) will report an error when the array overflows, and the compilation is prohibited.


how to prevent

1) In daily programming, develop good programming habits, analyze and check the upper and lower limits of array subscripts, and avoid the occurrence of array subscripts exceeding the limit and causing array overflow.
2) Array overflow may only occur in some special cases, which increases the difficulty of discovery. It can be combined with hardware to give a visual display of the abnormal operation of the program.


Guess you like

Origin blog.csdn.net/m0_64770246/article/details/128684266