Preventing buffer overflow in C/C++

南楼画角 提交于 2019-12-24 04:48:28

问题


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?


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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?




回答5:


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?




回答6:


using sprintf in TRACE MACROS is the biggest evil



来源:https://stackoverflow.com/questions/1083898/preventing-buffer-overflow-in-c-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!