-1

I seem to be having a problem where my compiler does not properly give me an exception when I access an index that is out of the bounds of the array.

For example: in my code I have

int reds[8][8];

This should create a 2d array with height 8(0-7) and width 8(0-7). The problem is, I have the following lines of code hereafter:

reds[0][8] = 1;
reds[0][65] = 1;

And my code compiles fine with no error. However, my program obviously does not work the way I want.

if(reds[r][column] > 0){
        if(column == 0) Red1_Write(0);
        if(column == 1) Red2_Write(0);
        if(column == 2) Red3_Write(0);
        if(column == 3) Red4_Write(0);

the if statement is gone into every time when it shouldnt. the values of the array at column 1 to 3 at row 0 was set to zero. What am I doing wrong?

James Le
  • 49
  • 6
  • 4
    Yes, you are confused about the language used. This is C, not Java. –  Dec 08 '13 at 18:01
  • 2
    I don't think C does bounds checking on arrays. It will, for the most part, let you do what you want and assume you know what you're doing... so you should certainly know what you're doing... – nhgrif Dec 08 '13 at 18:02
  • 3
    "*Exception*"? Which exceptions? – alk Dec 08 '13 at 18:06

1 Answers1

0

Welcome to "C". There are no bounds checking on arrays in "C". Accessing indexes off the end of an array results in undefined behavior (i.e. crashes and other strange behavior).

It is up to the programmer to code in such a way as to prevent this. If you have not yet done so, look into the C++ Standard Library (based on the old STL) which provides generic container classes that help you manage this type of situation. This would obviously only be useful if you can use a C++ compiler in your program.

STL: http://www.sgi.com/tech/stl/
Microsoft: http://msdn.microsoft.com/en-us/library/cscc687y.aspx

edtheprogrammerguy
  • 5,957
  • 6
  • 28
  • 47
  • 5
    "*it crashes*" if you're lucky. – alk Dec 08 '13 at 18:08
  • 4
    I'd be cautious about suggesting that out-of-bounds access results in crashes. Frequently, the program can access OOB memory just fine, leading to very strange behavior, but no crash. – abelenky Dec 08 '13 at 18:08
  • [In particular, `strlen()`](http://stackoverflow.com/questions/20312340/why-does-this-implementation-of-strlen-work). –  Dec 08 '13 at 18:10
  • Also, we are not using the STL anymore. What you are probably talking about is the C++ standard library. –  Dec 08 '13 at 18:10
  • 1
    question is only tagged c,array not c++ – qwr Dec 08 '13 at 18:19