Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

3
  • 1
    While it might seem trivial for the compiler to find out about in this simple scenario, it isn't simple in general. Just assume that the array was passed (as a pointer) into a function and the arithmetic was done in the function. How would the compiler know that the function wasn't called with &realarray[1] and the calculation thus valid? It's easy to create scenarios where you can't find out about this except at run-time. As a C or C++ programmer you have to watch out for these errors anyway. IMO there's more important things compiler writers should spend their resources on. Commented Mar 2, 2010 at 9:27
  • In this case, the array is not passed into the function as a parameter. It's scope is local, and checking the bounds in this case is something the compiler most certainly should do, since stack-smashing through stack-allocated arrays has been a security flaw in several programs. This sort of thing could only be useful in code where you know what the stack looks like, which depends on just about everything and the phase of the moon, and would better be done in assembler, where at least you have control over the stack use of your function. Commented Mar 2, 2010 at 13:58
  • A pointer can point to any location you like, whether you have reserved that memory or not. It's only when you come to read or write what's at that address that it becomes a problem since you will almost certainly get a segmentation fault. Try changing your example to read the int at the pointer location, and watch the sparks fly!! Commented Mar 2, 2010 at 16:15