user2172254
user2172254

Reputation:

new and delete Memory Management out of scope

void f(const Fraction& a)
{ Fraction b = a;
  Fraction* c = new Fraction(3, 4);
  Fraction* d = &a;
  Fraction* e = new Fraction(7, 8);
  Fraction* f = c;
  delete f;
 }
  1. Which values do I delete? I think I only delete c which is dynamically allocated and rest of the objects are destroyed automatically when the function ends.

  2. How about e? It is also dynamically allocated but we don't have any delete operator for e. The e is not de-allocated?

Thanks,

Upvotes: 1

Views: 1340

Answers (4)

Charles Salvia
Charles Salvia

Reputation: 53339

The key insight which you're probably missing here is that delete does not have any relationship with a specific variable - it has a relationship with a specific object stored at a certain memory address. It's commonly stated as a rule that "any object allocated with new must be deallocated with delete." But note the use of the word object - not variable.

Consider:

Fraction* a = new Fraction(3,4);
Fraction* b = a;
delete b;

In this example we deleted b, which points to the Fraction object allocated on the first line. We also could have deleted a, which pointed to the same Fraction object. As long as we delete every object allocated with new (regardless of which pointer variable we use to access the object), there is no memory leak. Also note that if we delete both a and b then we have an error (undefined behavior via a double-delete).

Upvotes: 5

ForEveR
ForEveR

Reputation: 55897

You should delete c (or f), but not both and you should delete e. For each new should be delete.

Upvotes: 4

fatihk
fatihk

Reputation: 7929

You should delete (c or f) & e

Upvotes: 1

alexrider
alexrider

Reputation: 4463

  1. You will delete object created with new Fraction(3, 4);
  2. Yes e or more strictly saying memory allocated with new Fraction(7, 8); will not be deallocated leading to memory leak.

Upvotes: 1

Related Questions