-4

I am not able to understand following behaviour in c++.I am using gcc 4.4.1

#include<iostream>
using namespace std;

class call{
        private:
        int *ptr;

    public :
    call()
    {
    cout<<"\nConstructor called\n";
    }

    void allocate()
    {
            ptr=new int[10];
    }

    void test()
    {
            cout<<"\nTesting\n";
    }

    ~call()
     {
            if(ptr)
            {

             cout<<"\nptr deleted\n";
             delete [] ptr;
                     ptr=NULL;
            }
      }
};





int main()
{
    call *p=new call();
    p->allocate();
    p->test();

    delete p;

    p->test();
    p->test();

    p->allocate();

    p->test();
    p->test();

return 0;
}

OUTPUT :

Constructor called

Testing

ptr deleted

Testing

Testing

Testing

Testing


In the above code , even after deleting object (delete p) , I am still able to access member function(void test()) of the class. How c++ is allowing me to access member function of the class if that object is deleted.

user1057741
  • 265
  • 1
  • 2
  • 10
  • There's good answer here: http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope – kotlomoy Jun 20 '13 at 18:28
  • 2
    Duplicate hundreds of times over. – Carl Norum Jun 20 '13 at 18:28
  • @CarlNorum I'm always wondering what leads people to try things that are wrong and then ask for a reasonable explanation... –  Jun 20 '13 at 18:29
  • It's not a null instance in this case, but that's also good information, and a freed pointer is analogous to a null pointer in that you certainly shouldn't be operating on them. – Carl Norum Jun 20 '13 at 18:30
  • will it fine if i call in following sequence in main() p->allocate(); p->test(); p->~call(); p->~call(); p->~call(); delete p; – user1057741 Jun 21 '13 at 09:50

3 Answers3

2

There's no reasonable explanation.

Your code invokes undefined behavior, and this means that it's not required to do anything particular. It can crash, but it doesn't need to do so. It can pretend to be "working fine", as in your case.

Maybe the memory manager on your OS didn't yet recycle the freed/deleted memory, that's all. But you should really not rely on this behavior.

  • will it fine if i call in following sequence in main() `p->allocate();` `p->test();` `p->~call();` `p->~call();` `p->~call();` `delete p;` – user1057741 Jun 21 '13 at 03:32
1

because after you did the following

delete p;

you didn't set p to NULL

try the following

void test()
{
    cout<<"Testing "<< ptr[0] << "\n";
}

void allocate()
{
     ptr=new int[10];
     ptr[0] = 10;
}
aah134
  • 860
  • 12
  • 25
0

Using a pointer after it's been freed causes undefined behaviour. That means anything can happen, including the appearance of "correct behaviour".

Carl Norum
  • 219,201
  • 40
  • 422
  • 469