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?
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?
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.
Don't use raw C-style arrays. Instead, use C++ container classes such as std::vector, which have the ability to check for invalid accesses and raise exceptions when they occur.
Also, what you are describing is not really a buffer overflow.
In addition to the other comments, you might also have a look at the suggestions in this thread, which deals with static code analysis tools:
http://stackoverflow.com/questions/632057/c-c-free-alternative-to-lint
In C++, one solution is to never use arrays, but C++ containers instead. Vectors, for example, have out of bounds detection if you use at intead of [] for indexing
In C, you should always design your functions such as you give the pointers and the dimension(s) of your arrays, there is no way around it.
A great tool for checking out of bounds access is valgrind. It works by running your binary unaltered, and can give the precise line where errors occurs if you compile with debug information. Valgrind work on many unix, including mac os x.
Note that valgrind cannot always detect those bad accesses (in your example, assuming it was a real out of bounds access, it would have gonve unnoticed by valgrind because the variable is on the stack, not on the heap).
Hello, I've found and interesting software for buffer overflow. You can free download it from www.bugfighter-soft.com
It says that it can discover buffer overflow and that it is independent from compiler and platform.
I tried it with Visual C++ Express 2008 and it worked well, I could discover buffer overflow in multidimesional array such int y[10][10][10];
Do you think it is cross platform?
Do you know something more about it?
Thanks
Best regards