When dealing with random memory overwrites, in MSVC it is possible to validate the state of the heap at various points with a call to _CrtCheckMemory, and know with at least a small level of confidence that the code up until the check was not res开发者_JAVA百科ponsible for any errors that might cause new or malloc to fail later.
In XCode, whats the equivalent way to try and box in a memory overwrite? All I have at the moment is a random failure of a call to new, somewhere deep in the bowels of some code with no real idea of how long the code has been running with a corrupt heap up until that point.
As it is only implied in Neil's answer, lets make this explicit:
As far as I know there isn't any tool that is as readily available as _CrtCheckMemory for gcc. IIRC there are some checked malloc libraries out there, but I didn't find them as usable as _CrtCheckMemory. There is however Valgrind which is deployed unintrusively, and gives you a much more throughout result.
This feature IS actually built into the heap in GCC.
As described here
The easiest way to enable it is on the XCode::Run menu: Enable Guard Malloc
This doesn't address your question directly, but I felt compelled to respond. As you say, tools like the CRT check functions only give you a small level of confidence, and don't address resource leaks other than memory. If you find yourself depending on such tools I would say there is something very, very wrong with your approach to C++ development. In the past 10 years, I have not had a single problem in my code associated with memory leakage. This is not because I am some C++ coding god, but because I use the basic tools of RAII, smart pointers and standard library collections in my code, and wherever possible avoid explicit dynamic memory allocation using new
. Whenever you find yourself writing a line of code like:
Something * p = new Something;
stop, and ask yourself "Is there some way I could avoid doing this?" and if the answer is "no", then ask yourself why you are allocating memory to a raw pointer, and if you can't find any way around that (which should very rarely be the case, immediately write the code to manage the pointers de-allocation, and make sure that that code is exception-safe.
If you take this approach, you won't need tools like special CRT functions or Valgrind, and you will save yourself oceans of time in debugging.
精彩评论