Reputation: 1894
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
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
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
Reputation: 171127
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 delete
ing it does nothing).
Upvotes: 1
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