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:
(substitute with correct C data type). Alternatively, there is
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 🙂