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.
Is it necessary to release memory by using if-statement?
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;
}
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With