0

I have created the following class :

class Deep {
private :
    int *ptr;
    string name;
    int age;
    double marks;
public :
    Deep() : ptr {&age}, name {"Mandeep"}, age {20}, marks {85.3} {
        cout<<"Deep Constructor Called for : "<<name<<endl;
    }
    ~Deep() {
        delete ptr;
        cout<<"Destructor Called for : "<<name<<endl;
    }
    void get_data() {
        cout<<"Name : "<<name<<endl;
        cout<<"Age : "<<*ptr<<endl;
        cout<<"Marks : "<<marks<<endl;
    }
};

int main() {
    
    Deep A;
    A.get_data();
    
    cout<<endl<<endl;
    return 0;
}

While running the program in Debugger, the program crashes at delete ptr;. Is delete ptr; no necessary here since I am not dynamically allocating any memory to *ptr ? Is *ptr already deleted by the destructor and then me trying to delete *ptr after causing the crash ?

LykanMD
  • 13
  • 4
  • 4
    `delete` has to match a `new`. You do not have a `new` in your code, so you cannot use `delete` valid. – mch Jul 21 '20 at 09:11
  • 2
    It's not about *necessity* - it's simply wrong to call `delete` on objects not allocated via `new` (like in your example). – P.P Jul 21 '20 at 09:12
  • You should not be using `new` or `delete` *at all* – Caleth Jul 21 '20 at 09:24

2 Answers2

1

delete operator can only be called on objects allocated with new. If you haven't allocated new memory, you cannot call delete operator.

Take the following example:

int main() {
    int a = 20;
    int* ptr = &a;
    delete ptr;
    return 0;
}

If you compile this code, it surprisingly(??) compiles without warning.

However, the debugger breaks the code at the call to delete operator.
delete_scalar.cpp:

_CRT_SECURITYCRITICAL_ATTRIBUTE
void __CRTDECL operator delete(void* const block) noexcept {
    #ifdef _DEBUG
    _free_dbg(block, _UNKNOWN_BLOCK);
    #else
    free(block);
    #endif
}

However, the following code works fine, as the memory has been allocated with new:

int main() {
    int* ptr = new int[5];
    delete[] ptr;
    return 0;
}
kesarling He-Him
  • 1,944
  • 3
  • 14
  • 39
  • so the destructor automatically destroys the pointer along with other data members ? – LykanMD Jul 21 '20 at 09:14
  • 2
    @LykanMD A pointer is just an address, i.e. a number, there is nothing to destroy. Don't mix destroying a pointer and an object it points to. If you set a pointer to point at some existing object, you shouldn't do anything to destroy the pointer itself. – Evg Jul 21 '20 at 09:17
  • 2
    @LykanMD This confusion seems to be the source of most newbie problems with pointers. The pointer and the thing it points to are two different things. – john Jul 21 '20 at 09:20
1

‘ptr’ is not pointing to allocated memory so no, you do not want to delete it. Only when ‘ptr’ is “owning” a memory that you need to delete it.