2

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?

2
  • You cannot do this inside your actual C++ code, q.v. this SO article, and I suspect you also won't be able to do it in the debugger. Commented Jun 5, 2015 at 7:35
  • Microsoft's Debug CRT will basically do this for you. When memory is deallocated it is overwritten with 0xDD so that you and the debugger can tell it shouldn't be used. See here for what 0xFD and 0xCD mean. Commented Jun 5, 2015 at 8:23

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.