Ste_95 Ste_95 - 5 days ago 5
C++ Question

Difference between accessing non-existent array index and existing-but-empty index

Suppose I wrote

vector<int> example(5);
example[6];


What difference would it make with the following?

vector<int> example(6);
example[5];


In the first case I'm trying to access a non-existent, non-declared index. Could that result in malicious code execution? Would it be possible to put some sort of code in the portion on memory corresponding to
example[5]
and have it executed by a program written like the first above?

What about the second case? Would it still be possible to place code in the area of memory of
example[5]
, even though it should be reserved to my program, even if I haven't written anything in it?

Answer

The first case reaches beyond the vector's buffer and thus invokes Undefined Behaviour. Technically, this means literally anything can happen. But it's unlikely to be directly exploitable to run malicious code—either the program will try to read the invalid memory (getting a garbage value or a memory error), or the compiler has eliminated the code path altogether (because it's allowed to assume UB doesn't happen). Depending on what's done with the result, it might potentially reveal unintended data from memory, though.

In the second case, all is well. Your program has already written into this memory—it has value-initialised all the 6 int objects in the vector (which happens in std::vector's constructor). So you're guarnateed to find a 0 of type int there.

Comments