Hi,
i got a program that crashing while i want to delete a pointer value. here is the code:

#include<iostream>
using namespace std;
class sab{
    int a;
public:
    sab(int x);
    ~sab();
    int get();
    sab(const sab &ob);
};
sab::sab(int x)
{
    cout<<"constructor"<<endl;
    a=x;
}
sab::sab(const sab &ob){
    cout<<"copyconstructor"<<endl;

}
sab::~sab(){
    cout<<"destructor"<<endl;
}
int sab::get(){
    return a;
}
int main()
{
    sab ob(5);
    sab *p;
    p=&ob;
    cout<<p->get()<<endl;
    cout<<ob.get()<<endl;
    delete p;
}

My question is why this program carashing, if i comment out delete p; only then the program run,please fix my code..

delete means "see this memory that I got using new? I don't need it anymore. Please run the appropriate destructor function and I don't care what you do with it after that."

You can only delete memory that you got using new. You didn't get any memory using new, so you can't delete it.

To fix your code, remove line 33.

thanks,for your reply. I understand that, but what i should do if i want to use delete p; ?
so, can you tell me where to add new so i can use delete p; ?
Thanks again.

Why would you need to delete p if it's not allocated by new? If you really want to "clear" out the p pointer, you could asign it to NULL.

If you really, really want to use delete, you have to use new.

int main()
{

sab* p = new sab(5);
cout<<p->get()<<endl;
delete p;
}

There is absolutely no need to use new here. I assume this is just so you can practice using new.

thanks..everyone

The pointer 'p' references a stack-based (automatic) variable. It cannot be deleted. As mentioned, only items that are created with operator new can be deleted. This can be a painful lesson to learn as it is a quick path to a core dump.

That said, an advanced C++ technique to deal with this may be to implement your own class operators new and delete (which is allowed, and often useful). The operator new would remember the pointer created in some collection, and delete would look it up. If it wasn't in the collection, it would do nothing. If it was, then it would delete the object and remove it from the collection (to avoid multiple deletes which is another quick path to core dump).

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.