Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ intentional out of range indexing [duplicate]

Tags:

c++

arrays

c

Say I have an array like so:

int val[10];

and I intentionally index it with everything from negative values to anything higher than 9, but WITHOUT using the resulting value in any way. This would be for performance reasons (perhaps it's more efficient to check the input index AFTER the array access has been made).

My questions are:

  1. Is it safe to do so, or will I run into some sort of memory protection barriers, risk corrupting memory or similar for certain indices?
  2. Is it perhaps not at all efficient if I access data out of range like this? (assuming the array has no built in range check).
  3. Would it be considered bad practice? (assuming a comment is written to indicate we're aware of using out of range indices).
like image 709
DaedalusAlpha Avatar asked Sep 13 '13 08:09

DaedalusAlpha


1 Answers

It is undefined behavior. By definition, undefined means "anything could happen." Your code could crash, it could work perfectly, it could bring about peace and harmony amongst all humans. I wouldn't bet on the second or the last.

like image 168
verbose Avatar answered Oct 21 '22 14:10

verbose