khajvah
khajvah

Reputation: 5090

Accessing non-existing array element

int main(int argc, char const *argv[])
{

    int anArray[5];

    anArray[0] = 54;
    anArray[1] = 54;
    anArray[2] = 54;
    anArray[3] = 54;
    anArray[4] = 54;
    anArray[5] = 54;
    anArray[6] = 54;
    anArray[7] = 54;


    printf ("%i\n", anArray[7]);

    return 0;
}

This prints 54.

How does this even work? We say that C arrays are not dynamic. Why should this even compile? or even if it compiles, it should throw a seg fault.

I have defined an array of 5 elements, then I accessed elements 5,6,7. Why is it possible to assign a value to, for example, anArray[5]?

Please note that I have a c++ background and I haven't used this kind of array for a long time.

Upvotes: 2

Views: 2247

Answers (4)

Kaustav Ray
Kaustav Ray

Reputation: 754

No compiler error: as no compiler error related issues.

Run time error: because of undefined behavior and you are lucky that the memory location you

were trying to access was free at that time !

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258618

The language itself doesn't say the runtime or the compiler has to check you're actually accessing elements inside the bounds of the array. The compiler could emit a warning, but that's it. You are responsible for accessing valid elements. Not doing so results in undefined behavior, which means anything can happen, including appearing to work.

Upvotes: 2

John Zwinck
John Zwinck

Reputation: 249153

You are scribbling into memory that you don't own, so anything could happen. You got lucky and the computer let you write and then read the value in that location. But it's just luck: the behavior is undefined.

Note that the exact same thing applies to C++ (since you mentioned it), not only with C-style arrays but also with std::vector::operator[] and std::array in C++11. In C++ you can use vec.at(idx) instead of vec[idx] to do bounds checking always.

Upvotes: 3

Octoshape
Octoshape

Reputation: 1141

You're basically reading into memory to places where you don't know what's there. This can be a useful thing in C (if you really know what you're doing) but also can get you hours of frustrating debugging because it is undefined behaviour what's going to happen there.

From wikipedia:

Many programming languages, such as C, never perform automatic bounds checking to raise speed. However, this leaves many off-by-one errors and buffer overflows uncaught. Many programmers believe these languages sacrifice too much for rapid execution.

Upvotes: 0

Related Questions