Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to use IF statement when releasing memory? [duplicate]

Tags:

c++

pointers

I am trying to understand memory part in C++. I am trying to release memory after I generate the output by using the code below.

Question:

Is it necessary to release memory by using if-statement?

Code:

int main(){
    char *pc;
    int *pi;

    pc = new char('a');
    pi = new int(8);

    cout << *pc << endl;
    cout << *pi << endl;

    //What's the purpose for doing if(pc) and if (pi) below?

    if(pc){
        delete pc;
    }
    if(pi){
        delete pi;
    }

return 0;
}

Could I be able to do in this way? int main(){ char *pc; int *pi;

    pc = new char('a');
    pi = new int(8);

    cout << *pc << endl;
    cout << *pi << endl;


    delete pc;
    delete pi;

return 0;
}
like image 904
14K Avatar asked May 16 '13 22:05

14K


2 Answers

Is it necessary to use IF statement when releasing memory?

No, it is not (as long as you haven't overridden the global operator delete). This is perfectly fine and will do nothing:

int* p = nullptr;
delete p;

Per paragraph 3.7.4/2 of the C++11 Standard:

[...] The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect. [...]

As suggested by chris in the comments, however, consider using smart pointers rather than performing manual memory management through raw pointers, new, and delete (or their array counterpart).

like image 119
Andy Prowl Avatar answered Oct 26 '22 23:10

Andy Prowl


In your particular code, the null checks are not needed.

In general, it's implementation specific whether delete (T*)0; will call the deallocation function for type T. If your implementation does pass null pointers to the deallocation function, and either your type has overridden the deallocation function by providing member operator delete, or you're provided a replacement global ::operator delete, and that custom deallocation function doesn't handle null pointer values well, you could have trouble.

The Standard does NOT require that a custom operator delete do nothing when passed a null pointer. It shouldn't fail, but it might write nasty log messages or tell your boss that someone isn't following the coding standard, for example.

like image 35
Ben Voigt Avatar answered Oct 26 '22 22:10

Ben Voigt