-1

The pointer *sbi memory is freed using the delete operator but still the code executes correctly without providing garbage value. is the constructor re-initializing or is the a fault in code/

#include <iostream>
using namespace std;

class bank
{
private:
    int balance;
public:
    bank();
    void dep(int x);
    void with();
    ~bank();
};
int main()
{
    bank *sbi;
    sbi = new bank;
    sbi->dep(50000);
    delete sbi;   /// problem is in this section of code 
    sbi->with();
    return 0;
}

bank :: bank()
{
    balance=0;
}

void bank::dep(int x)
{
    balance=x;
}

void bank::with()
{
    cout<<balance<<endl;
}

bank::~bank()
{
    cout<<"destroy"<<endl;
}
gameon67
  • 3,981
  • 5
  • 35
  • 61
Varun
  • 21
  • 7
  • 3
    Memory doesn't magically cease to exist or become unavailable or change its contents. Dereferencing a pointer to memory you don't own leads to [*undefined behavior*](https://en.wikipedia.org/wiki/Undefined_behavior). Once you've free'd memory (through `free` or `delete` or `delete[]`) you should no longer attempt to dereference the pointer (unless you reassign it to point to some valid memory). – Some programmer dude Jan 10 '19 at 08:41

1 Answers1

2

Freeing a memory location does not automatically overwrite it with garbage. By coincidence, that value stored in balance is still the same.

Julian
  • 64
  • 7
  • Note also, it's not guaranteed to be or remain the same. As soon as the memory location is re-allocated and re-written the value will change and so cannot be relied upon as accessing it is undefined behaviour and a source of many many hard to find software bugs in the past. – Rich Jan 10 '19 at 10:17