How dangerous is it to access an array out of bounds?

How dangerous is accessing an array outside of its bounds (in C)? It can sometimes happen that I read from outside the array (I now understand I then access memory used by some other parts of my program or even beyond that) or I am trying to set a value to an index outside of the array. The program sometimes crashes, but sometimes just runs, only giving unexpected results.

Now what I would like to know is, how dangerous is this really? If it damages my program, it is not so bad. If on the other hand it breaks something outside my program, because I somehow managed to access some totally unrelated memory, then it is very bad, I imagine.
I read a lot of ‘anything can happen’, ‘segmentation might be the least bad problem’, ‘your hard disk might turn pink and unicorns might be singing under your window’, which is all nice, but what is really the danger?

My questions:

  1. Can reading values from way outside the array damage anything
    apart from my program? I would imagine just looking at things does
    not change anything, or would it for instance change the ‘last time
    opened’ attribute of a file I happened to reach?
  2. Can setting values way out outside of the array damage anything apart from my
    program? From this
    Stack Overflow question I gather that it is possible to access
    any memory location, that there is no safety guarantee.
  3. I now run my small programs from within XCode. Does that
    provide some extra protection around my program where it cannot
    reach outside its own memory? Can it harm XCode?
  4. Any recommendations on how to run my inherently buggy code safely?

I use OSX 10.7, Xcode 4.6.

11 Answers
11

Leave a Comment