Now that I don't get any errors from valgrind to start with, what can I do to find the memory corruption problem in this complex and big application?
Well let me describe to you what I did to find memory leaks in Microsoft's implementation of JavaScript back in the 1990s.
First I ensured that in the debug version of my program, as many memory allocations as possible were being routed to the same helper methods. That is, I redefined malloc
, new
, etc, to all be synonyms for an allocator that I wrote myself.
That allocator was just a thin shell around an operating system virtual heap memory allocator, but it had some extra smarts. It allocated extra memory at the beginning and end of the block and filled that with sentinel values, a threadsafe count of the number of allocations so far, and a threadsafe doubly-linked list of all allocations. The "free" routine would verify that the sentinel values on both sides were still intact; if not, then there's a memory corruption somewhere. It would unlink the block from the linked list and free it.
At any point I could ask the memory manager for a list of all the outstanding blocks in memory in the order they had been allocated. Any items left in the list when the DLL was unloaded were memory leaks.
Those tools enabled me to find memory leaks and memory corruptions in real time very easily.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…