I'm working with visual studio IDE, I need to break my program at a particular place if a pointer at the same line pointing to a invalid memory (already deleted memory). is there a way to do that?
3 Answers
If you control the type pointed to, yes.
Add a field int already_destroyed and set it to 0 in the constructors, and to a nonzero value in the destructor. Even if the debug CRT overwrites it, it still will be non-zero. In Visual Studio, use a conditional breakpoint with condition already_destroyed != 0.
Theoretically non-portable, but I suspect the idea will work in more environments.
Comments
As this Stack Overflow article discusses, you cannot determine whether a pointer is valid or not in your C++ code. The main reason for this is that there would be a lot of overhead in maintaining the state of each pointer. The Visual Studio debugger uses C++ code for its functionality, so the same holds true there. That being said, you can monitor the memory to which each of your pointers is pointing, by either typing the pointer name in the watch list, or inputting it in the Memory window (Debug -> Windows -> Memory). However, note that the pointer itself won't necessarily tell whether the memory it points to is valid or invalid.
Comments
If you need a kind of "post mortem" solution, there is always the possibility of using PageHeap. This way, if your program tries to access free'd or otherwise invalid memory, the CRT will cause a __debugbreak. But be aware that this solution will bloat your memory consumption so don't forget to disable it afterwards!
All informations you need: PageHeap @ MSDN
0xDDso that you and the debugger can tell it shouldn't be used. See here for what0xFDand0xCDmean.