Search code examples
c++memoryconstructorreturnallocation

What do I do if constructor fails to allocate memory in C++?


I just came across a problem where the constructor of a class needs to allocate memory. So I happily wrote char *mem = static_cast<char*>(malloc(100*sizeof(*mem)));. But then I suddenly realized that in case of error I can't return error code (I am not using exceptions in my code). How can I solve this problem?

Should I add an bool initialized member and then after making my class and then check it right after, as in:

myClass mc;
if (!mc.initialized) {
    printf("Memory allocation failed in mc's constructor\n");
    exit(1);
}

Thanks, Boda Cydo.


Solution

  • You should use new, not malloc. new throws std::bad_alloc when you are out of memory. An exception should be propagated from the constructor if you fail to allocate (or for any other reason have a problem with initialization), as this is the only way you prevent the destructor from being called. If the constructor successfully completes, the destructor must be called (unless, of course, it was heap allocated and never freed).