1

It is correct to use delete on nullptr in classes like that or should I avoid solutions like here?

class Ar{
    public:
    Ar();
    Ar(int n);
    ~Ar();
    void setT(int n);
    void remT(int n);
    int* ptr;
};
Ar::Ar() : ptr(nullptr) {};
Ar::Ar(int n) : Ar(){
    ptr = new int[n];
}
Ar::~Ar(){
    delete[] ptr;
}
void Ar::setT( int n ){
    delete[] ptr;
    ptr = new int[n];
}
void Ar::remT( int n ){
    delete[] ptr;
    ptr =  nullptr; // #1
}
int main(){
    Ar temp;
    temp.setT( 5 );
    temp.remT( 5 );
    return 0;
} // #2

On #2 destructor will try delete[] ptr, where ptr==nullptr so will do nothing. But if instruction #1 does not exist program will crash on #2 with double free or corruption error.

michalm
  • 11
  • 1
  • I know it is safe to use delete on nullptr but I don't know I should or shouldn't do that in eg. destructors. – michalm Sep 12 '16 at 20:58
  • Why would the rule change in a destructor? – Nicol Bolas Sep 12 '16 at 21:12
  • "I'm a cowboy - Should I wear belt *and* braces?". "Depends. You won't lose your pants, but you might still lose your colt without noticing." Memory leaks should be prevented by proper coding, not unnecessary `delete`s 'just in case'. – tofro Sep 12 '16 at 21:13
  • 1
    Anyway this code has a problem, that if `setT` throws an exception when it calls `new`, then the old value of `ptr` has been deleted, but it's still stored in the object and will be deleted again by the destructor of `temp`. So think more carefully about what the valid states are of the object: "storing a pointer that's already deleted" should not be one. At the same time decide whether `nullptr` represents a valid state of the object: if so then go ahead and delete `ptr` whether it's null or not, but make sure `ptr` always contains something you can delete. – Steve Jessop Sep 12 '16 at 21:18
  • Ok, thank you all for answers. – michalm Sep 13 '16 at 10:28

0 Answers0