segmentation fault while delete..

HI,
I am gettin a segmentation fault while deleting an object,
I have defined an object

CStopWord* F1=new CStopWord("stopwords.txt");

some operations

delete F1;

then in the constructor of call i m using

CStopWord::~CStopWord()
{
delete(this);
}

But in delete this i m gettin a segmentation fault...

Please help me with this
The destructor is there to free memory you newd in the constructor, it doesn't free itself (that is what delete does). Btw, calling delete inside the constructor on this will just call the destructor again, and you will probably get a stack overflow.
You can't delete "this"... you don't need to anyway.

When you use new, at some point you need to use delete on that thing you used new on. You should also be careful with your pointers and check to see that they actually point to something before trying to delete.

Temporary variable: If you mess with memory yourself, then you have to unmess it yourself.
1
2
3
4
5
6
void func()
{
    something *a = new something;
    //...do stuff
    delete a;
}


Classes: The point here is that the class automates the messing with memory.
1
2
3
4
5
6
7
8
9
10
class someclass
{
  private:
     something *a;
     something2 *b
  public:
    someclass() { a = new something; }
    ~someclass(){ if(a) delete a; if(b) delete b; }  //check before delete
    void amethod() { b = new something2; }
};
Last edited on
Topic archived. No new replies allowed.