I was playing around with arrays in C++ and wrote this simple code 👇
include
using namespace std;
int main() {
int marks[5] = {23, 22, 33, 43, 50};
cout << marks[8] << endl;
return 0;
}
Guess what happened?
💥 Output: 4199048
No error. No warning. Just a random number.
At first I thought something was wrong with my compiler, but then I realized:
👉** C++ does not check array bounds.**
That means if you try to access an index that doesn’t exist, it still “works” — but you’re reading from some random place in memory.
This is called undefined behavior, and it’s one of those sneaky things that make C++ both powerful and dangerous.
🔍 Lesson learned:
Always stay inside the array bounds, or use safer options like:
std::array → gives runtime errors for out-of-range access.
Cplusplus #Programming #LearningInPublic #DSA #DeveloperJourney #CodingTips
std::vector → safer and more flexible dynamic arrays
💡 Sometimes, the best way to understand programming is by breaking it (accidentally 😅).
Top comments (0)