Arumand
Arumand

Reputation: 1894

Why this global heap object not freed?

I have this code:

class A {
    public:
            int x;
};

A *b;

void x() {
    A a;
    A *b = new A();
//  delete b; // works. free b.
}

int main() {
    x();
    delete b; //not. why ?
    return 0;
}

why b can only be freed inside x() ? not main() ? I thought b is a manual variable, and not scope bound. Checked with valgrind.

Thank you. :)

Update:

Now i remembered. I can use global b with :

b = new A();

Then the delete b on main() can properly delete global b.

*facepalm*

Upvotes: 0

Views: 98

Answers (4)

billz
billz

Reputation: 45410

You could manipulate outter b this way:

 ::b;

inside function x(), you declared a new b which shows b in global. You could provide scope resolution notation :: if you want to operate on outter b.

Upvotes: 2

pmr
pmr

Reputation: 59811

The b inside x is different from the b in global scope. I don't know what a "manual" variable is supposed to be, but C++ is (for all practical purposes) lexically scoped. So a new variable hides a variable at a higher scope level.

Upvotes: 0

In your function x(), you're declaring a local variable b. This variable is unrelated to the global variable b.

delete b in main() tries to delete the global pointer b (which, being global, is initialised to a null pointer value, so deleteing it does nothing).

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272537

Because the declaration of b inside x() shadows the global declaration; it's a separate variable. So in your code, the global b is never assigned to, so you have a memory leak.

Upvotes: 6

Related Questions