Why do compilers not warn about out-of-bounds static array indices?

前端 未结 10 1678
心在旅途
心在旅途 2020-12-03 03:07

A colleague of mine recently got bitten badly by writing out of bounds to a static array on the stack (he added an element to it without increasing the array size). Shouldn

相关标签:
10条回答
  • 2020-12-03 03:54

    shouldn't the compiler emit a warning at the very least?

    No; C compilers generally do not preform array bounds checks. The obvious negative effect of this is, as you mention, an error with undefined behavior, which can be very difficult to find.

    The positive side of this is a possible small performance advantage in certain cases.

    0 讨论(0)
  • 2020-12-03 04:01

    There are some extension in gcc for that (from compiler side) http://www.doc.ic.ac.uk/~awl03/projects/miro/

    on the other hand splint, rat and quite a few other static code analysis tools would have found that.

    You also can use valgrind on your code and see the output. http://valgrind.org/

    another widely used library seems to be libefence

    It's simply a design decision ones made. Which now leads to this things.

    Regards Friedrich

    0 讨论(0)
  • 2020-12-03 04:02

    The C philosophy is that the programmer is always right. So it will silently allow you to access whatever memory address you give there, assuming that you always know what you are doing and will not bother you with a warning.

    0 讨论(0)
  • 2020-12-03 04:06

    The reason C doesn't do it is that C doesn't have the information. A statement like

    int a[10];
    

    does two things: it allocates sizeof(int)*10 bytes of space (plus, potentially, a little dead space for alignment), and it puts an entry in the symbol table that reads, conceptually,

    a : address of a[0]
    

    or in C terms

    a : &a[0]
    

    and that's all. In fact, in C you can interchange *(a+i) with a[i] in (almost*) all cases with no effect BY DEFINITION. So your question is equivalent to asking "why can I add any integer to this (address) value?"

    * Pop quiz: what is the one case in this this isn't true?

    0 讨论(0)
提交回复
热议问题