Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined behavior beyond the max index of an array

Situation:

I'm taking a crash course to get familiar with C, and I've noticed that the author of this course can print array values beyond the array's index and be confident that the value will be 0 each time.

Code from crash course below:

int arrayVar[] = {45, 67, 34, 23};
printf("This array index value is %d", arrayVar[4]);

Output from code:

This array index value is 0

It's been my experience, during this tinkering/testing of C, that once you go beyond the array's max index, you're entering undefined behavior territory, where anything can happen, so how can he be so confident (and right) about seeing a 0 value every time?

If I print values beyond the array's max index, I see "random" values (or, values that were left there in memory, right?).

Why is my experience different from what I'm seeing in this course? Is this just a difference in C standards? Or does this indicate a difference in compilers? Or both?

Environment info : I am using the C11 standard, and I'm using the compiler that (I'm pretty sure) came default with ubuntu, located at /usr/bin/cc.

EDIT: For anyone interested in seeing what I'm seeing, here's a link to the course (you'll probably be prompted to login to Udemy): https://www.udemy.com/c-fast-crash-course-introduction/learn/lecture/12868540#questions

Sample Image

like image 717
Joshua Schlichting Avatar asked Dec 07 '22 11:12

Joshua Schlichting


1 Answers

The author of the course is wrong.

It's that simple.

like image 186
Lightness Races in Orbit Avatar answered Dec 25 '22 00:12

Lightness Races in Orbit