Why this code is working? , You can try on VSCode and online compiler | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why this code is working? , You can try on VSCode and online compiler

https://code.sololearn.com/chnFN7f70r6Y/?ref=app

23rd Nov 2022, 8:40 PM
Dharmendra Pandit
Dharmendra Pandit - avatar
4 Answers
+ 3
Declaring array size just 5 but accessing it's beyond it's boundaries.. Error. or undefined behavior..
23rd Nov 2022, 8:48 PM
Jayakrishna 🇮🇳
+ 1
Trying to access array elements beyond it's bounds is an Undefined behaviour in C/C++. Because of this, a lot of implementations doesn't perform a check for this by default . If your program tries to access an illegal memory location ( memory that doesn't belong to that program ), your operating system terminates the program by throwing a segmentation fault. The only reason why this program might work in some cases is because your program has been allocated more memory.
24th Nov 2022, 12:33 AM
Arsenic
Arsenic - avatar
+ 1
This question is answered, however i want say here that this code is perfectly fine. The error you get is not a C++ exception, but OS exception. In reality if you try to run this code under other OS it may work. You get this exception because the most operating systems nowdays have limitations on what each application can access in system memory.
24th Nov 2022, 3:07 AM
Giannis
Giannis - avatar
+ 1
c++ lets you access some values beyond your array. Why it is so is beyond me. It's like having no fence on the edge of a cliff. So it's proceed at your own risk. https://www.geeksforgeeks.org/accessing-array-bounds-ccpp/ btw, your example should be: (It thows an error in Sololearn if the items are more than 10, but values can be stored in undefined regions.) #include <iostream> using namespace std; int main() { int n=5; int array[n]={12,57,45,8,6,86,8,6,8,42}; cout<<array[9]; return 0; }
24th Nov 2022, 5:00 AM
Bob_Li
Bob_Li - avatar