Dynamic Memory

Suppose I allocate memory with a statement
char* c=new [char];
and then create a new reference to this storage area by
char* x=c;
Suppose that later in the program I do not know whether the memory pointed to by x (or c) has in the meantime been deallocated or not. Is there a way to check?
No. You must keep track of that yourself.

The proper way to do it is to use NULL:
1
2
3
4
5
6
7
8
9
10
11
char* s = NULL;  // Doesn't point to anything

s = new char[ 50 ];

...

if (s)
  {
  delete [] s;
  s = NULL;
  }

Hope this helps.
Thanks much Duoas. Now I know that there is no pre-defined C++ function which will help me.

If I applied your suggestion to my hypothetical case, and I decided at some point to decallocate the memory to which c pointed, I would place the code

if(c) {delete c; c=NULL;}

Now if I remembered that x pointed to where c pointed, I could just check the truth of the expression c==NULL.

The problem is, what if I did not recall that x pointed to c, and needed to check to see if the memory to which x pointed was deallocated? Perhaps there IS no good solution?
There is a way using boost::shared_ptr<> and boost::weak_ptr<> (www.boost.org).
Topic archived. No new replies allowed.