Finding memory corruption of a C++ class member variable using GDB

Source: Giant Water Bug by FreeLearning

Today I managed to catch a nasty bug of memory corruption of a C++ class member variable. This was related to a C cast being used in place of dynamic_cast. But more interesting is the way I caught the bug.

Luckily, the class that we saw get corrupted was the label, the corruption was very visible (a bool variable that should be permanently true was set to false) and the instance that we saw get corrupted was the game’s loading screen. Setting the breakpoint was easy, especially since I could easily just set it inside the constructor: loading screen contained the very first label instance that was created in the game.

Now, we were lucky that the memory that was corrupted was in our code. We were also very lucky to be able to pinpoint what gets corrupted before it gets corrupted.

Catching where it got corrupted could be a bit trickier if it weren’t for GDB.

So once the code stopped in the constructor, we issued this command manually to GDB:

watch -location mTextFormatted

This creates a hardware watchpoint that breaks execution when the location is read. You can alternatively use this syntax if you want to watch a specific memory location:

watch *((int*)0xdeadbeef

(substitute with correct C data type). Alternatively, there is rwatch and awatch. Read more on Stack Overflow

Xcode turned out to be very nice here. When the watchpoint is hit, it shows a sheet that alerts you pretty strongly that it was hit. Read more on Stack Overflow

Helpful post? Don’t forget to comment 🙂


via blog.vucica.net

Leave a Reply

Your email address will not be published.

 

What is 10 + 13 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)

This site uses Akismet to reduce spam. Learn how your comment data is processed.