No runtime error

Hello.

Quick question...

When I write:

string a(&data[3], data);

...this should exit the program with a error message like "string out of bound", but at the moment I dont get a message at all

What should I do ? I'm using MSVC compiler
Last edited on
Accessing an array out of bounds is undefined behavior. The best thing for it to do would be to immediately crash your program, but it doesn't have to.

If you want to add bounds checking that will throw an exception, the simplest way would be to use a std::vector or std::array and change your data[i] calls to data.at(i).

https://www.cplusplus.com/reference/array/array/
https://www.cplusplus.com/reference/array/array/at/
It throws out_of_range if n is out of bounds.


It's also not clear what string constructor that code would be using.
Last edited on
In the future, include the types of all objects used in the code. If we don't know the types we don't know the semantics, and thus the code is meaningless to us.
It's a out of range problem. My previous compiler showed the runtime error when I did something like in my example. I didnt have to create a vector or an array.

Maybe it's a compiler setting/option that needs to be turned on?
> Maybe it's a compiler setting/option that needs to be turned on?

g++ / clang++: -fsanitize=address
https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html#Instrumentation-Options

MSVC command line: /fsanitize=address
MSVC IDE: Properties => Configuration Properties => C/C++ => General => Enable AddressSanitizer
https://docs.microsoft.com/en-us/cpp/sanitizers/asan?view=msvc-160
Last edited on
Note that checking for bounds issues can significantly slow execution speed. That's why c++ doesn't have it by default.
use .at() instead of [] which would alert you? (try catch block)
or handle it yourself... if(string.length() > 2)
else.. something
we tested .at a while back and its performance hit is substantial if you are iterating something of size. For one letter no one will notice.
Last edited on
does string support .at()

Sure it does. https://en.cppreference.com/w/cpp/string/basic_string/at
Thanks! I fixed it above
JLBorges, thanks I'll try it out,


Note that checking for bounds issues can significantly slow execution speed. That's why c++ doesn't have it by default.

Ok thanks, so I can have these settings turned on while I develop the app, then turn it of for the release


use .at() instead of [] which would alert you?

Thanks for the tips but maybe I'll make some other mistakes as well, so i'll try to to get the compiler to nag as much as possible while I develop
Last edited on
[] doesn't do a range check. at() does.
Using at() will cause an exception to be thrown if you attempt to access out of range, so it's a really good way of finding mistakes you've made.
Topic archived. No new replies allowed.