Answer the question
In order to leave comments, you need to log in
How to throw an "array out of bounds" exception?
Let's say we have this bad code.
chartext[10];
cin.getline(text,15);
How to handle this error?
Answer the question
In order to leave comments, you need to log in
It is important to understand here that C ++ is close enough to the hardware and does not control your actions. If you access data outside of the array, you do so at your own risk. C++ does not prevent you from doing this. But what happens if you do this? There are two outcomes. The most likely one is that you will simply read memory beyond the bounds of the array. What will happen there is unknown. Maybe just trash. May be part of another variable. Unknown. Those. further behavior of the program will depend on how your program will work with this garbage. If you write something outside the array, you will either end up in an unused area of memory or mess up other variables. This error is called memory corrupt and is one of the worst errors when working with C/C++.
Less commonly, you'll get a "memory access violation" exception. This will happen in cases where the array out of bounds also falls outside the bounds of the allocated memory pages. Roughly speaking, you get to addresses where there is no memory at all. For example, windows gives the program 4k pages of memory. There seems to be no memory outside these pages, and any access there causes a memory access exception.
Well, now what to do.
Usually pure C-style arrays are not used in C++ for exactly the above reasons. Not safe. As a rule, a wrapper for an array is written in C ++ (or a ready-made one is used) and access is carried out through specially written access functions, the so-called. getters and setters, which control the exit from the limits. And they can already throw exceptions or otherwise report an error.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question