Jump to content
SSForum.net is back!

Recommended Posts

Posted

Debugged another memory error recently. I came up with the following strategy, which seems to work pretty well. The symptom of memory corruption is that something that is obviously correct doesn't work (for example, a data structure appears inconsistent which leads to a crash). I would create a function to do a sanity check on the data structure, and then, if it fails, exit immediately (after printing some debug information about the point at which the sanity check failed). I would have a function like:

 

runSanityCheck(const char* messageIfFailed);

 

 

then I would call this very often in the code (I did it in the in the module manager before every callback). When I run the program now, it would eventually fail the sanity check, which gives you a range of places where the corruption may have occured (between the time it failed and the previous call to the sanity check code). You can then do a binary search on your code by inserting more sanity checks until you get to a piece of code doing a write to dynamic memory, which is probably the memory that was freed at some point but is being written to anyway (and corruptioning your data structure in the process).

  • Replies 55
  • Created
  • Last Reply

Top Posters In This Topic

Posted

I think gdb can do data breakpoints so it'll break every time a specific memory location is accessed. I think it can even be made to break only on certain data conditions. Might make your debugging process a bit easier.

Freedom is the right to be wrong.
Posted

Have you tried valgrind memcheck? That tool has saved me a lot of time.

 

Just a thought, have you ever considered using garbage collecting with C?

Posted

Sounds like a nasty patch to hide bad coding, imo...

 

That, or ref-counted pointers... Which can be useful in some cases, but you can't use them everywhere easily. And it doesn't guarantee anything, as you can still use the data pointer directly and do nasty things with it.

 

Google came up with this: http://www.linuxjournal.com/article/6679

Posted (edited)

I do not have a lot of experience with it myself. I have used the C++ boost library before though.

This was in a small experimental project that used an event loop (C++ module for asss that lets you use RPC in Java and Python using thrift). All the main logic is on the main thread which is a big loop, I/O is done asynchronously using threads and callbacks (events). Boost's shared_ptr uses reference counting to destroy objects. Manually calling free / delete would be awful using an event loop. The reason why I used shared_ptr was because the library thrift required them, however I was pleasantly surprised afterwards.

Edited by JoWie

×
×
  • Create New...