In C++, unless you use advanced features, if memory cannot be allocated with the new
operator, an exception is thrown, so the there is no need to check if the pointer obtained by new
is null or not. Handling the exception is up to the programmer. If you don't, the program will terminate abruptly. It is actually tricky to handle this exception properly and restart the operations without memory or resource leaks, which is why allocation of objects with new
and delete
is now considered obsolete. Using containers and smart pointers is a better alternative.
Note that you can get the same behavior in C with a wrapper on malloc()
:
#include <stdio.h>
#include <stdlib.h>
void *xmalloc(size_t size) {
void *p = malloc(size);
if (p == NULL) {
fprintf(stderr, "malloc failed for %zu bytes\n", size);
exit(1);
}
return p;
}
There is no need to check for memory allocation failure by xmalloc()
since such a failure causes an abrupt program termination automatically. This approach can be used for command line utilities where failure is not catastrophic and can be handled interactively.