Hello Everyone,

Need your comments on :

"Can over running of array lead to the catastrophic failures ? "
May be the answer is YES.

"Then, why does not c++ provide bound checking on array operations and who is responsible to prevent array overruns ?"



9 Years
Discussion Span
Last Post by Duoas

Any language, regardless of error checking, or garbage control, can be prone to serious security flaws or generic bugs.

In the end you can't control who writes the code.


C was designed with the BCPL concept that the programmer knows what he is doing, even if he wants to shoot himself in the foot (or, in C++, blow his whole leg away).

This design structure led to the problem is that it is not always possible to keep track of where the array ends. Consider:

#include <stdio.h>

void print( char string[], int length ) {
  int i;
  for (i = 0; i < length; i++)
    putchar( string[ i ] );

int main() {
  char salutation[] = "Hello world!";
  print( salutation, 500 );
  return 0;

If you compile and run this code you'll probably get a segmentation fault (a memory access violation).

Inside main(), the compiler knows that salutation shouldn't be indexed past 12, and any attempt to do so should result in a compile-time error.

However, once you pass it off to print(), you've thrown away all the information about the actual size of the array. You could easily call print() many times, each time with a different array of a different length.

Predictably, char string[] is really the same as char *string . The compiler has no way of knowing how long the array addressed by string[] is. It relies entirely upon you, the programmer, to make sure that you don't go too far.

So, in C languages (that includes C++), it is the programmer's responsibility to make sure he/she never permits array overruns.

It is entirely possible to keep metadata with an array. For example, the compiler could make an array as a structure containing both a pointer and a length field. Conceptually:

struct {  /* this represents a pointer */
  unsigned long length;
  whatever *data;

Or, the array itself could be headed by the length:

struct {
  unsigned long length;
  whatever data[ length ];  /* pointer points to data[ 0 ] */

The latter method is basically how Delphi handles strings (well, it's actually a tad more complex than that...).

Now, the compiler can add code that checks to see whether or not an index tries to access something too big or small before actually making the attempt.

The drawback is that this bloats things with stuff under the covers. C is designed to be as anti-under-the-covers-bloat free as possible.

Hope this helps.

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.