I have a rather simple question, and I' ve been looking for the answer for awhile, but did not find any.
So I would like to know, what is the proper way of deleting a pointer.

For example I have a class with some kind of array, which I want to extend later. But what if, for some reason, I won't have to. Like, I am opening a file, but it is not there, so I don't need to allocate any memory. Eveything is OK, then destructor starts working and then the whole program crashes. Altough It works fine if it had some amount of memory allocated before.
So would you please show me the proper way of deleting pointers?

Thank you very much.

myClass::~myClass()
{
	if( my_array != 0 )
	{
		 delete []my_array;
	}	
}

I didn't want to off, so if it is just kill it. 'SOORY'

Recommended Answers

All 4 Replies

Initialized the pointer to 0 if you aren't allocating memory. You can safely delete a null pointer and it will effectively be a no-op.

The question should be asked "how do I delete a pointer if I allocate the memory using xxxx?"

Let us review:

if you write

double* Ptr=new double[50];    // Allocate space for 50 double s
// ... other code
delete [] Ptr;                             // Delete the pointer to 50 doubles
// CARE:
// Ptr is still pointing to a value

but if you write

double* Ptr=new double;        // allocate 1 double 
//.... other code
delete Ptr;                       

Note as pointed out, delete removes the memory for the pointer BUT does not change the value of the pointer variable. e.g.

double *Ptr=new double[50];
std::cout<<"Ptr memory location == "<<reinterpret_cast<long int>(Ptr)<<std::endl; 
delete [] Ptr;
std::cout<<"Ptr memory location == "<<reinterpret_cast<long int>(Ptr)<<std::endl; 
// 
// THIS CAUSES A RUNTIME ERROR:
// DO NOT DELETE TWICE
//
delete [] Ptr; 

Note in the above example , if you set Ptr=0; after the first delete then all is well.

Finally::

double X[50];        
//.... code
// NO DELETE Required:
// THIS CAUSES A RUNTIME ERROR:
delete [] X;    

If the pointer is from an object that is not allocated via a new then don't delete it.

Note: that if you are using malloc etc, then you must use free. If you are not using malloc, then don't start using it.

Hope this helps

use the free() function for delete the space occupie by pointer


syntax :

free(pointer name)

Now I get it. Thank you all of you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.