Trt Trt
Trt Trt

Reputation: 5552

Strange Array Behaviour

I have this function that takes an array of 512 Vertices. (each one containing x,y,z coordinates). Anyway, I made a mistake and instead of accessing the array 512 times, I did it 513 times. Instead of "zeros" I got a number. I run it again, the same. I increased the iterations and the same thing again. Even though I was going beyond the limits of the array random values were showing up each time I the function. What are those values? Am I accessing anything in the OS? (it may sound stupid but im new to C++ and pointers)

void print_facet_array(FACET3 *f)
{
    int i=0;
    for (i=0;i<=513;i++)
    {
        printf("The vertices (x,y,z) for facet %d are: V_1 =  x:%f , y:%f, z:%f. \n", i, f[i].p1.x, f[i].p1.y, f[i].p1.z);
        printf("The vertices (x,y,z) for facet %d are: V_2 =  x:%f , y:%f, z:%f. \n", i, f[i].p2.x, f[i].p2.y, f[i].p2.z);
        printf("The vertices (x,y,z) for facet %d are: V_3 =  x:%f , y:%f, z:%f. \n", i, f[i].p3.x, f[i].p3.y, f[i].p3.z);
    }

}

Upvotes: 2

Views: 350

Answers (3)

Alok Save
Alok Save

Reputation: 206646

Accessing an array beyond its bounds results in Undefined Behavior.
Undefined Behavior means that anything can happen and all safe bets are off.

So those values can be anything really, they are values present at some memory location which was not reserved for your array.They might belong to some other valid variable maybe or not.

Just remember NEVER to access array elements beyond its bounds.

Since you are starting to learn C++, this should be a good read:
What every c programmer should know about Undefined Behavior.

Upvotes: 4

Zach Rattner
Zach Rattner

Reputation: 21361

C and C++ do not support array bounds checking. Unlike Java, where accessing an array outside of its legal bounds will cause an exception to be shown, C++ allows the access. In short, congratulations; you've created dice (a random-number generator).

The values you're seeing after you reach the end are whatever happens to be in memory after the last element. It might be an old variable, another variable, or just garbage from an uninitialized block of memory.

Upvotes: 0

Mysticial
Mysticial

Reputation: 471559

Actually, your loop goes through 514 times. So you're overrunning by 2.

Overrunning an array in C/C++ is completely undefined behavior. Anything can happen (crash, bad data).

In your case, you're probably reading stack or heap garbage - which can be anything.

Upvotes: 4

Related Questions