开发者

Tools for Dealing with Stack Corruption in c++

开发者 https://www.devze.com 2023-02-05 18:48 出处:网络
EDIT: Due to a comment that was开发者_StackOverflow中文版 right about my example I removed it and turn this into a generic question:

EDIT: Due to a comment that was开发者_StackOverflow中文版 right about my example I removed it and turn this into a generic question:

Some times in my projects I come across stack corruption. No matter how much I fight to write code to avoid it, sometimes it is just unavoidable. But when it happens what are the ways to fight it?

I found one macro given by the good fellow in this blog: http://rxwen.blogspot.com/2009/04/detect-stack-corruption.html which reads the ebp register value to detect corruption.

But there are bound to be more sophisticated tools to help with not shooting yourself on the foot. I am programming in Windows using Codeblocks and the gcc compiler. The reason I make this question is to find tools which I can use under my programming environment to help me detect such mistakes and correct them. Any suggestions?

Thanks for any answers and for taking the time to read my question.


It's far from unclear that you are having stack corruption. But I accept there is some data corruption.

A reasonably effective technique is to add guard fields around the suspect field(s):

...
long   namecheck1;
Artist artist;
long   namecheck2;
...

Have the constructor initialize these to most anything, but without knowing the nature of the corruption something non-zero seems more satisfying.

myclass::myclass() : namecheck1(0x12345678), namcheck2(0x12345678) ...

Add a consistency check member function:

void myclass::isokay()
{
       if (namecheck1 != namecheck2  ||
           namecheck2 != 0x12345678)
             cerr << "the object is corrupted";
         ... // maybe wait for input, cause core dump, etc.
}

Then pepper the code with calls to this, especially near suspicious logic. If you are comfortable with a debugger, place a breakpoint on the error message. By unraveling the stack, you can ascertain what the program has done recently and gather clues as to what bit of code is probably writing outside the proper bounds.


Valgrind finds all kinds of memory corruption.

GCC has mudflap (-fmudflap and friends) and -fstack-protector to catch memory access problems. Other compilers probably do, too.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号