1
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,

  • 1
    `delete` doesn't delete a variable. It deletes allocated memory which a pointer variable points to. – leemes Apr 22 '13 at 11:08
  • 2
    You have two `new`s and one `delete`. You are leaking one `Fraction`. – juanchopanza Apr 22 '13 at 11:08
  • 3
    I guess the third line is not even possible. You are pointing at a const object with a (non-const) pointer. – leemes Apr 22 '13 at 11:10
  • A more essential question: why are you dynamically allocating `Fraction`, when it manifestedly supports copy and assignment? – James Kanze Apr 22 '13 at 11:13
  • Yeah that was my mistake. I was trying to find which values are deleted and which objects are deleted as well. THanks! –  Apr 22 '13 at 11:21

4 Answers4

5

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).

Community
  • 1
  • 1
Charles Salvia
  • 52,325
  • 13
  • 128
  • 140
4

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

ForEveR
  • 55,233
  • 2
  • 119
  • 133
1
  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.
alexrider
  • 4,449
  • 1
  • 17
  • 27
1

You should delete (c or f) & e

fatihk
  • 7,789
  • 1
  • 26
  • 48