Memory leaks in constructions

Say that you have found somewhere deep in the darkest basement the following line of code

then you have found a potential memory leak in your program.

Why?

Remember that, calling new Date() will:

  1. Allocate memory for Date
  2. Construct the new Date object in that memory. If the construction fails because of an exception, then the allocated memory is freed again.

The compiler is free to evaluate the expressions in any way it seems suitable (the reason for this is that it has the ability to optimize the code if given some slack, see order of evaluation).  It can for example do like this:

  1. Allocate memory for Date
  2. Construct Date
  3. Allocate memory for Time
  4. Construct Time
  5. Call fun

The problem here is that if either step 3 or step 4 fails because of an exception, the C++ standard does not require that the Date object must be destroyed and its memory deallocated. This is a memory leak!

Another possibility is that the compiler does this:

  1. Allocate memory for Date
  2. Allocate memory for Time
  3. Construct Date
  4. Construct Time
  5. Call fun

In this case, then there are actually two problems.

1) If step 3 fails because of an exception, then the memory allocated for Date is automatically deallocated (step 1 is undone), but the standard does not require that the memory allocated for the Time object be deallocated. The memory is for the Time object is leaked.

2) If step 4 fails because of an exception, then the Date object has been allocated and fully constructed, but the standard does not require that it be destroyed and its memory deallocated. The memory of the Date object is leaked.

 

 

 

 

Facebookgoogle_pluslinkedinmail