There is a thing that I don't understand in C++. To contrast, in C when we call malloc
we check if the allocation failed to then free all the previously allocated memory so as to make a clean exit without memory leaks.
But in C++ no one seems to care about that with the new
operator. I know that it throws std::bad_alloc
on failure, but if there were previous successful allocations with new
we are left with memory leaks upon a thrown exception, aren't we?
In my example the memory leaks are still reachable, but it could be some definitely lost memory.
int main(void) {
int *ptr1 = new int;
int *ptr2 = new int;
// do something with ptrs
delete ptr1;
delete ptr2;
return (EXIT_SUCCESS);
}
Whereas in C we'd do
#include <stdlib.h>
int main(void) {
void *ptr1;
void *ptr2;
if (!(ptr1 = malloc(10)))
return (EXIT_FAILURE);
if (!(ptr2 = malloc(10))) {
free(ptr1);
return (EXIT_FAILURE);
}
//do something with ptrs
free(ptr1);
free(ptr2);
return (EXIT_SUCCESS);
}
So shouldn't we do something like this instead given std::bad_alloc
can be thrown?
#include <new>
int main(void) {
int *ptr1 = new int;
int *ptr2;
try {
ptr2 = new int;
} catch (std::bad_alloc &e) {
// do something with exception
delete ptr1;
return (EXIT_FAILURE);
}
// do something with ptrs
delete ptr1;
delete ptr2;
return (EXIT_SUCCESS);
}