Tools for working with stack corruption in C ++

EDIT: Due to a comment that was right regarding my example, I deleted it and turned it into a general question:

Several times in my projects I come across stack corruption. No matter how much I am afraid to write code to avoid this, sometimes it is simply inevitable. But when this happens, what are the ways to deal with it?

I found one macro given by a good person on this blog: http://rxwen.blogspot.com/2009/04/detect-stack-corruption.html that reads the value of the ebp register to detect damage.

But there are even more sophisticated tools that will help you not shoot in the leg. I program on Windows with Codeblocks and a gcc compiler. The reason I ask this question is to find tools that I can use in my programming environment to help me detect such errors and fix them. Any suggestions?

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

+8
c ++ stack corruption
source share
2 answers

It is far from clear that you are facing corruption. But I agree that there is some data corruption.

A fairly effective method is to add protective fields around a suspicious field:

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

Ask the constructor to initialize them for most things, but without knowing the nature of corruption, something non-zero seems more satisfactory.

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

Add member function consistency check:

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

Then rewrite the code for calls, especially near suspicious logic. If you are comfortable working with the debugger, put a breakpoint in the error message. By expanding the stack, you can find out what the program has done recently, and collect hints as to which bit of code is likely to be written outside the appropriate boundaries.

+4
source share

Valgrind finds all kinds of memory corruption.

GCC has mudflap ( -fmudflap and friends) and -fstack-protector to catch memory access issues. Probably other compilers do too.

+1
source share

Source: https://habr.com/ru/post/651191/


All Articles