Prince of Persia
Prince of Persia

Reputation: 49

I get an unexpected outcome for square array?

I get the outcome for squares

squares = [ 512, 1, 4, 9, 16, 25, 36, 49 ].

I know I reached the boundaries of my limit but where did 512 come from? Can you give me an explanation of all the individual steps involved in the error occurring?

int main()
{
    unsigned squares[8];
    unsigned cubes[8];
    for (int i = 0; i <= 8; i++) {
        squares[i] = i * i;
        cubes[i] = i * i * i;
    }
}

Upvotes: 0

Views: 37

Answers (3)

sjsam
sjsam

Reputation: 21965

You're accessing memory beyond the limit

for (int i = 0; i <= 8; i++) 

should be

for (int i = 0; i <8; i++) 

Remember unsigned squares[8]; allows you to legally access squares[0] upto squares[7]

I know i reached the boundaries of my limit but where did 512 come from.

The consequences of illegal memory access is undefined as per ISO/IEC 9899:201x 6.5.10->fn109

Two objects may be adjacent in memory because they are adjacent elements of a larger array or adjacent members of a structure with no padding between them, or because the implementation chose to place them so, even though they are unrelated. If prior invalid pointer operations (such as accesses outside array bounds) produced undefined behavior, subsequent comparisons also produce undefined behavior


You may use a debugger(say gdb) or an instrumentation framework(say valgrind) to find where the value came from. Here 512 looks like the cube of 8 but there is no guarantee that you will get the same value on the next run. Morever, there is a chance that the program might crash.

Upvotes: 1

Haris
Haris

Reputation: 12272

I would say the same thing as everyone is saying. It is undefined behavior and you should not do that.

Now, you would ask whether the undefined behavior is the reason for whatever is happening.

I would say, Yes, probably.


Now, you may think this is an easy escape from answering the question.

It may be, but..

The main problem with these kind of question is, it is very hard to re-create the same case and investigate what actually made it behave the way it did. Because undefined behavior, well, behaves in a very undefined way.

That is the reason people do not try answering these kind of questions, and people advise to stay away from undefined behavior territory.

Upvotes: 1

Sourav Ghosh
Sourav Ghosh

Reputation: 134356

I know i reached the boundaries of my limit

Then you should know the consequences, too. Accessing out of bound memory invokes undefined behavior.

Stay within the valid memory limit. Use

for (int i = 0; i <8; i++) 

Upvotes: 1

Related Questions