Losiowaty
Losiowaty

Reputation: 8006

Why didn't this crash?

So, I have this code :

int randomNumber;
int max = 16;
int swap;
int table[16];

srand(time(NULL));
for (int i = 0; i < 16; ++i)
    table[i] = i + 1;

for (int i = 0; i < 16; ++i) {
    randomNumber = rand() % max;
    swap = table[max];
    table[max] = tablica_losowa[losuj];
    table[losuj] = swap;
    --max;
}

Obviously, the problem should be in first pass through the second for-loop when max == 16 and I try to access table[max], but it compiled and runs fine.

This is from an iPad(newest soft) application, written in Objective-C, XCode 4.6, Apple LLVM Compiler 4.2.

Any hints?

Upvotes: 0

Views: 75

Answers (2)

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81868

The problem is that C (and Objective-C) does not give any guarantees regarding "undefined behavior". The array out of bounds access table[16] is such undefined behavior (see C11 standard 6.5.6).

This "giving no guarantees" in case of undefined behavior goes very far. Your program then is free to do anything. It could take a picture from the webcam and post it on facebook, send an offensive email to your boss and then start formatting your hard drive. Though not very likely, this behavior would be totally valid in terms of what the language says it does.

So, just ignoring the error and continuing to execute the program is obviously fine, too.

Upvotes: 0

mah
mah

Reputation: 39807

Accessing a memory location owned by something else does not guarantee a crash, it only guarantees you're doing something you shouldn't. What will happen is depended on what the memory location is and how it is used.

The compiler is simply not doing anything to cause a problem here. Objective C is based on C... it's a little tighter in some ways but C will let you try to do lots of things no matter how invalid, as long as the syntax is correct. In your case, writing to table[16] could be writing to a memory location that isn't important. It might be writing to swap, which then gets overwritten. Check the assembly to be certain.

Upvotes: 3

Related Questions