Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory Allocation Exception in Constructor

I have a constructor that allocates several blocks of memory using the new operator.

X::X() {
    a = new int[100];
    b = new char[100];
    c = new float[100];
}

My question is, if the allocation of c fails, and the constructor throws an exception, will the memory for a and b be automatically freed?

like image 290
wahab Avatar asked Feb 25 '16 14:02

wahab


People also ask

Will a constructor allocate memory if it throws an exception?

No. If an exception occurs during the Fred constructor of p = new Fred(), the C++ language guarantees that the memory sizeof(Fred) bytes that were allocated will automagically be released back to the heap.

Does a constructor allocate memory?

A constructor does not allocate memory for the class object its this pointer refers to, but may allocate storage for more objects than its class object refers to. If memory allocation is required for objects, constructors can explicitly call the new operator.

When memory is allocated to a constructor in C++?

When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated. Use the delete operator to deallocate the memory allocated by the new operator.

What happens if memory allocation fails in CPP?

In the above example, if new fails to allocate memory, it will return a null pointer instead of the address of the allocated memory. Note that if you then attempt indirection through this pointer, undefined behavior will result (most likely, your program will crash).


2 Answers

The memory to which a and b point would not be automatically freed. Every new[] must be balanced explicitly with a delete[].

Even if your destructor performed the deletion (assuming a, b, and c are class members), then you'd still leak memory. That's because the destructor wouldn't be called in this case since the object failed to construct.

Using std::vectors would obviate these problems.

like image 57
Bathsheba Avatar answered Oct 12 '22 01:10

Bathsheba


a, b, and c will all be destroyed. Depending on what types they are, that might or might not release the memory. If they are pointers their destructors don't do anything, and the memory leaks. If they are some sort of smart pointer, presumably their destructors will release the memory.

like image 41
Pete Becker Avatar answered Oct 12 '22 01:10

Pete Becker