0

I have written code to sort elements of an array. It works fine but i don't understand why it works. I expected an IndexOutOfBounds error. But nothing of the sort happens. I thought I "had to" use

SIZE - 1 // in the for loops but even SIZE works fine. THAT IS MY PROBLEM

the question in Array index out of bound in C doesn't clearly explain why i get correct results after sorting the array. below is the code:

#include <stdio.h>
#include <stdlib.h>
#define SIZE 12     //  definition
int main(int argc, char *argv[])
{
    int a[ SIZE ] = {12, 9, 10, 7, 6, 8, 5, 1, 3, 2, 4, 11};
    int i;
    int j;
    for( i = 0; i < SIZE; i++ ) 
    {
        for (  j = 0; j < SIZE; j++ )  // why not SIZE - 1 ????
        {
            if( a[j] > a[j + 1])
            {
                int hold = a[ j ];
                a[ j ] = a[ j + 1 ];
                a[ j + 1] = hold;
            }
        }
    }
    for( i=0; i < SIZE; i++ )
    {
        printf( "%4d", a[ i ] );
    }
    return 0;
}
Community
  • 1
  • 1
guthik
  • 404
  • 1
  • 7
  • 15
  • 3
    C doesn't automatically test array bounds. – Barmar May 26 '15 at 21:41
  • you might want to post this on code review stack exchange – Dan Beaulieu May 26 '15 at 21:42
  • @assylias He said that in the question. He's not asking how to code it correctly, he's asking why the incorrect code isn't reporting an error. – Barmar May 26 '15 at 21:43
  • C has no mechanism for checking array bounds. It works because there's nothing checking that it shouldn't. However, all sorts of problems could possibly arise if your code routinely goes out of bounds –  May 26 '15 at 21:44
  • I was tempted to flag this question as off-topic, "why isn't this code working," but in reality it should be "why does my bad code work?" – JAL May 26 '15 at 21:44
  • Yes, you are right @Dan Beaulieu. it gives correct results. – guthik May 26 '15 at 21:45
  • @JAL, i think you misread it. i did not write "why isn't this code working", i wrote: "Why does my code work?" I think i said what i meant. – guthik May 26 '15 at 21:48
  • 2
    Run it under Valgrind and it will tell you when and where you run out of your arrays. – Jongware May 26 '15 at 22:06

2 Answers2

3

C doesn't check array bounds, so it incidentally works as long as you have access to the last item.

You might get other errors, though, if you run this code more often. Since you are altering a piece of memory that doesn't belong to the array, you might get all kinds of (un)expected behavior. Yes, Qix, including Access violations :)

Since you have very low values in your example array, the chances are high that the value in that extra int is higher. If so, it will remain at the end of the array, and it's never overwritten. It may take a long time before you get any error from this code, but you probably will, eventually.

So, sometimes it will work, other times it will not. This also relates to the rest of your application and the kind of data that is there. It might be that you never (or almost never) get the error, and then you make a change and recompile and suddenly you will get it all the time. Also, you may accidentally change the memory (swapping the last item), which will give you an incorrect array (one item is replaced by another), and it may lead to weird situations, because you also changed a value in some other variable.

So, long story short, it's hard to predict what exactly will happen.

GolezTrol
  • 114,394
  • 18
  • 182
  • 210
  • 4
    Or, you know, an access violation... – Qix - MONICA WAS MISTREATED May 26 '15 at 21:46
  • mhm, so what you are saying is that soemtimes it will work just fine. but after a while it will report the errors or sometimes it will work fine and other times it will not? is there some sort of threshold after which it will not work? – guthik May 26 '15 at 21:50
  • Indeed, Sometimes it will work, other times it will not. This also relates to the rest of your application and the kind of data that is there. It might be that you never (or almost never) get the error, and then you make a change and recompile and suddenly you will get it all the time. Also, you may accidentally change the memory (swapping the last item), which will give you an incorrect array (one item is replaced by another), and it may lead to weird situations, because you also changed a value in some other variable. It's hard to predict what exactly will happen. – GolezTrol May 26 '15 at 21:55
  • @GolezTrol, this last comment is clearer and more convincing than both your answer and the answers to the "possible duplicate" :)) If you don't mind, i want to vote this one as the correct answer – guthik May 26 '15 at 21:58
  • because once i had an almost similar situation with pointers, the program seemed rather straight forward but the output was completely different from the expected results. Now i think i understand why that happened :) – guthik May 26 '15 at 21:59
  • I'm glad I eventually described it right. I've added the comment to the answer. – GolezTrol May 26 '15 at 22:01
1

You might be getting the sorted values. But not one can make sure that you will get always sorted values or set of values as your initialized array has.

Accessing the out-of bound memory in C is undetermined behavior. Even in your case, as you are accessing the very next location of your reserved memory and using it to swap the values at index SIZE and SIZE+1. Thus, if you check your output carefully, you might be getting the sorted array (luckily) but you must be seeing the one elements different which you might not be having in your initialized array..

Amit Sharma
  • 1,987
  • 2
  • 18
  • 29