I found a negative index access in an embedded code I'm debugging:
for (int i = len; i > 0; i--)
{
data[i - 1] = data[i - 2]; // negative access when i == 1
}
I read this about similar cases, but in the OP arr[-2]
is guaranteed to be OK since arr
points to the middle of a previously allocated array. In my case, data
is a pointer inside a class that is initialized by the constructor with:
public:
constructor_name(): ... data(new T_a[size]), ...
And the pointer data
is the first member in the class:
template <class T_a, class T_b, int size>
class T_c
{
private:
T_a *data;
T_b *...;
int ...;
int ...;
int ...;
public:
constructor_name(): ... data(new T_a[size]), ...
Now, is there a possibility that the negative index access was deliberate and was meaningful? Is there a way the programmer who wrote that was able to ensure that data[-1]
will access a specific datum, using #pragma pack ()
or other any methods?
Seeing *data
is the first member in the class made me think it was a bug, but I'm not sure. If it is indeed a bug - is it UB
?