1

I have the following code:

class A {
public:
    virtual void f() {
        cout << "1" << endl;
    }
};

class B : public A {
public:
    void f {
        cout << "2" << endl;
    }
};

int main() {
    A* a = new B();
    a->f();
    return 0;
}

And my question is: why there is no need to to delete a before return of the main function? According to my understanding this code will result in a memory leak, am I wrong?

[UPDATE] I checked the following code using valgrind and it confused me even more. It says there is a memory leak.

triple fault
  • 13,410
  • 8
  • 32
  • 45
  • The type will at least store the address of it's member functions, so I'd say that whoever told you this was wrong. – OMGtechy Oct 05 '14 at 15:35
  • 1
    It's not as much a *leak* as it is just something you haven't cleaned up. It's a proper leak once you actually forget the reference, e.g. if you had said `a = nullptr;`. Leaks are always bad, whereas leaving something unreclaimed at the end like that is sometimes done. – Kerrek SB Oct 05 '14 at 15:44

2 Answers2

1

There is indeed a memory leak. It lasts from the return of main to the exit of the program, which in this case is very, very short.

MSalters
  • 173,980
  • 10
  • 155
  • 350
0

"According to my understanding this code will result in a memory leak, am I wrong?"

No you're right, there should be a delete. Though the memory leak usually doesn't matter, since the OS will reclaim all memory allocated from the process after return 0;.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190