现在的位置: 首页 > 综合 > 正文

how to debug buffer overrun

2013年08月09日 ⁄ 综合 ⁄ 共 1903字 ⁄ 字号 评论关闭

最近开发一套基于InfiniBand的网络通讯组件,在使用InfiniBand通讯前,我使用socket来进行同步,在服务端开发中遇到这样的一个问题:A buffer overrun has occurred in IBConnection.exe which has corrupted the program's internal state. Press Break to debug
the program or Continue to terminate the program.

For more details please see Help topic 'How to debug Buffer Overrun Issues'.  c++的内存管理实在让人蛋疼,找半天没有找到可能导致缓冲区溢出的地方,最后google搜索到一篇关于这方面的文章,按照里面的的提示,一步一步排查,最终得到解决。原文是英文的(http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/29243438-a5ef-404c-8b02-81e039a03459/),现摘录如下:

Hmm, you must have had a pretty big overrun on the stack to cause that. Most likely you have a string which wasn't null terminated and you then used strlen to count the length.

Have you used strncpy in your program? If you have then you have to remember that it doesn't add the null character if the length of the string is longer than the value you pass to it.

 

I can't say much for other people but this is the general things I do to find out where a buffer overrun is occuring.

 

1) Keep an additional variable for each string containing the length of the string.

2) Step through each function which contains string operations and check the sizes of each string and make sure there is enough room.

 

Other things which I do to help prevent things like this.

 

1) Never allocate a string on the stack. All strings I create are on the heap.

2) All strings are created with a maximum possible length. If there is any string inputted then it is truncated to the maximum length.

3) I don't reuse buffers if I don't need to. If I want to put a string into memory, it is either a readonly constant or I allocate the buffer just as I copy the string, freeing any previously allocated
memory first.

4) I have a custom strlen function which takes the maximum possible size of the string as a parameter. This means, if the target buffer is 51 chars then I will pass 50 as a parameter to the strlen function.
If it is more than 50 chars then it will return 50 otherwise it will return the length of the string.

5) I always explicitly have one character reserved for the null character. If I allocate enough room for a 40 character string, I will make sure that I allocate 41 characters worth of memory.

6) I always initialise the entire buffer to 0 before I use it.

抱歉!评论已关闭.