Preventing buffer overflow in C/C++

buffer-overflow, c, c++

Solution

Neil's answer is better in the general case, but if you have a reason for using plain old arrays, you can use functions to get and set the values and also check that you're within the array bounds:

#define MAX_INDEX 10

int y[MAX_INDEX][MAX_INDEX][MAX_INDEX];

int get_y(int a, int b, int c)
{
    ASSERT(a >= 0 && a < MAX_INDEX);
    ASSERT(b >= 0 && b < MAX_INDEX);
    ASSERT(c >= 0 && c < MAX_INDEX);
    return y[a][b][c];
}

void set_y(int a, int b, int c, int value)
{
    ASSERT(a >= 0 && a < MAX_INDEX);
    ASSERT(b >= 0 && b < MAX_INDEX);
    ASSERT(c >= 0 && c < MAX_INDEX);
    y[a][b][c] = value;
}

...all wrapped up in a class, ideally.

Problem

Many times I have problems with Buffer Overflow. ``` int y[10][10][10]; ``` ... ``` y[0][15][3] = 8; ``` How can I prevent this problem? Is there any good tool that can help me?

Original source