How to determine where memory leak is, in C++ not by using any tools
I have a memory leak in my program, and I am trying to determine where it is lea开发者_如何学运维king.
If you can shed any light on this subject please do.
Since the question (now) says "not using any tools", then you are probably reduced to looking at the source code. One place to look is at the constructors and destructor of each class.
- Is all the memory allocated by your constructors released by your destructor?
- If other methods in your class allocate memory, is that memory released by your destructor?
Otherwise, look for instances of new
(in all its varieties) and ensure you can establish where the allocated memory is released.
And, if you are misguided enough to mix C memory allocation via malloc()
, realloc()
, and free()
in with your C++ code, then do a similar exercise on every allocation, ensuring you know where the corresponding release is. (I assume that you would never attempt to delete
space allocated by malloc()
nor free()
space allocated by new
.)
Consider whether you should be using one of the various automatic pointer manager classes to ensure that memory is released.
You are probably better off using the tools available to highlight where the leaks occur.
If you refuse to use other tools, you're pretty much stuck with the human eyeball, version 1.0. Unfortunately, unless the code is pretty trivial, this probably won't be easy. I don't mean to sound nasty saying it, but memory leaks are incredibly rare in well designed code. That means there's all too good a chance that the code you're working on has some fairly serious problems to start with, in which case finding leaks by inspection is more likely than not to be quite slow and painful.
The obvious starting points for the inspection would be all uses of new
, malloc
, calloc
, etc., and (should-be) matching calls to delete
, free
, etc.
Check out the _CrtDumpMemoryLeaks() function of the crtdbg class
Profiling tools should be able to help. For example:valgrind
Also, you can try to check all the warning messages from your compiler.
Edit: I missed the part about "without tools".
Checking compiler warnings I think is a good first step.
You can also try putting debug statements around all your free/delete code to make sure you are freeing something valid.
Look for common bugs like: "delete ptr" instead of "delete [] ptr".
Just do a grep/search for all the "new" and "delete" statements in your code and see if they make sense.
精彩评论