-1

I am currently doing some dynamic programming in C++ using QT creator. Is there a way to know if a piece of memory that I allocated dynamically is emptied out at the end of a function?

EDIT: I am trying to find if the memory is emptied after I attempted to deleted. Not check if a pointer is valid.

Alperen AYDIN
  • 547
  • 1
  • 6
  • 17
  • Can you show an example of what you what to do? – NathanOliver May 17 '16 at 12:04
  • Please provide how you are allocating memory. If you are using malloc/calloc,then check for return value against null. – Manthan Tilva May 17 '16 at 12:05
  • Are you sure that you're doing [dynamic programming](https://en.wikipedia.org/wiki/Dynamic_programming)? – molbdnilo May 17 '16 at 12:05
  • If youre' wondering if there is a (standard) way to determine whether a particular part of memory has been deallocated, then no. You can avoid that problem through the use of smart pointers. – molbdnilo May 17 '16 at 12:08
  • Possible duplicate of [C++ Is it possible to determine whether a pointer points to a valid object?](http://stackoverflow.com/questions/17202570/c-is-it-possible-to-determine-whether-a-pointer-points-to-a-valid-object) – PcAF May 17 '16 at 12:10
  • If you allocated the memory using malloc() . You should define your own free () function so that you can set the pointer to NULL after freeing it. In this way you can check whether pointer is valid pointer or not before accessing it. Similarly you should count total number of references to a variable in c++ and delete that pointer after reference count reach to zero. Don't forget to set the pointer to NULL. – The Philomath May 17 '16 at 12:21
  • @NathanOliver I have a virtual pure class 'obstacle', and there are two classes that inherit from it: circle and polygone. In another class, I have a vector of pointers to 'obstacle', and I fill it up using functions that dynamically create the obstacles. – Alperen AYDIN May 17 '16 at 12:25
  • What do you mean by "emptied"? – Jean-Baptiste Yunès May 17 '16 at 12:27
  • @Jean-BaptisteYunès I mean it was deleted. – Alperen AYDIN May 17 '16 at 12:29
  • I really sugest you use a `std::unique_ptr` or `std::shared_ptr` and leave the memory management to the instance itself. Then when you erase the element from the vector it is handled correctly and nothing else needs to be done by you. – NathanOliver May 17 '16 at 12:32
  • If you allocated it dynamically (`new`) and if you used `delete` then it is deleted... – Jean-Baptiste Yunès May 17 '16 at 12:52

1 Answers1

1

Well, I assume you mean "released" instead of "emptied".

If you have a pointer variable, always set "nullptr" to it at the begining. If you release the pointer, always set "nullptr" to it.

You can always check, if the pointer is equal to nullptr, of so, it's released. There is no simple way how to check, if an address contains a valid object.

wh1sp3r
  • 1,640
  • 2
  • 17
  • 30