简体   繁体   中英

Preventing buffer overflow in C/C++

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:

C/C++ Free alternative to Lint?

Solution at the code level

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.

Solution at the tool level

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).

I've found an interesting software for buffer overflow. You can download it for free 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 a multidimensional array such int y[10][10][10];

Do you think it is cross platform?

Do you know something more about it?

在TRACE MACROS中使用sprintf是最大的罪恶

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM