check for memory leak in c++
I have a code of about 10,000 lines. I have to maintain a track for new and delete statements to check and avoid memory leaks. i can use new libraries or functions but i can't change the code. How can i do it? P开发者_开发知识库lease donot suggest for any memory cheking tool.
Any help would be appreciated.
i can use new libraries or functions but i can't change the code.
Link to a heap implementation, which implements the global new and delete operators, and which keeps track of how many times each one is called.
HI ChrisW, Thanks for your reply. I implemented your suggessted way. it is working but i also want to know that, on which file and at which line these statements were used? Thanks in Advance
There are two ways to do that.
The global new operator needs to look at (and perhaps decode) the call stack when it's invoked, to see/remember where it's being called from each time it's called.
See the answers to Overriding “new” and Logging data about the caller
On Unix platform, you can use the LD_PRELOAD
variable to substitute (at runtime) a library, this giving the opportunity to bring in you own new
and delete
operator.
This way, you can use implementation which will check for the allocations and deallocations, and you can (for example) print the callstack for every error.
On linux not sure about other OS you can use a tecnique called: interposing.
You can override default C++ memory allocator, but you'd need to change your calls to new then. Another alternative is to override low-level function calls such as malloc, effectively that is what memory debugging libraries do (if that's your homework it's likely that you need to do exactly that). One more way is to change the code in a way so that you add a pointer to some set when you allocate memory in new, and then remove a pointer from the set when you call delete (that would be more a rookie way of doing things, but should work), and then check before existing application (or some other event when you expect your memory to be free), that you have an empty set of pointers.
精彩评论