Since x
is not really validated and is received through scanf, there should be potentially tainted data that can be used to access bytes
.
Code (not really logically doing anything productive):
void getMyBytes(){
int x, byte;
int bytes[20];
scanf("%u %u", &x, &byte);
bytes[x-1] = byte;
}
A known simple (ugly) fix for this code is:
void getMyBytes(){
int x, byte;
int bytes[20];
scanf("%u %u", &x, &byte);
if (x > sizeof(bytes)/sizeof(*bytes)) return; --> validation fix
bytes[x-1] = byte;
}
What inputs can I enter in scanf so that I can access bytes
?
This depends on your application but you should always bound check external input when accessing your internal members. How you report this is up to you. But consider using the std::vector
or std::array
to help you out. In your example:
void getMyBytes(){
int x, byte;
std::array<int, 20> bytes; // Bad name btw, an int is very unlikely to be a byte.
scanf("%u %u", &x, &byte); // scanf is not type safe. Consider using cin <<
bytes.at(x-1) = byte; // Automatically bound checks for you and will throw an exception
// in the case that you are out of bounds. Very useful :)
}
Returns a reference to the element at specified location pos, with bounds checking. If pos is not within the range of the container, an exception of type std::out_of_range is thrown.
Other ways you might report the error include:
assert(x >= 0 && x < bytes.size() && "I crashed here because you gave me bad input!")
if (x < 0 || x > bytes.size()) { return false; }
if (x < 0) { throw my_special_underrun_exception; }
and if (x > bytes.size()) { throw my_special_overrun_exception; }
Finally consider visiting the CppCoreGuidelines for plenty of tips about how to write good code.