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?

Nayana Adassuriya
  • 23,596
  • 30
  • 104
  • 147
  • You cannot do this inside your actual C++ code, q.v. [this SO article](http://stackoverflow.com/questions/17202570/c-is-it-possible-to-determine-whether-a-pointer-points-to-a-valid-object), and I suspect you also won't be able to do it in the debugger. – Tim Biegeleisen Jun 05 '15 at 07: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](https://msdn.microsoft.com/en-us/library/974tc9t1.aspx) for what `0xFD` and `0xCD` mean. – sjdowling Jun 05 '15 at 08:23

3 Answers3

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.

MSalters
  • 173,980
  • 10
  • 155
  • 350
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.

Community
  • 1
  • 1
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
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

nshct
  • 1,197
  • 9
  • 29