Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leaking memory when assigning new value to variable?

Yes, I'm one of those fellows that is learning C++ coming from Java, being spoiled with an automatic garbage collector. There's a particular situation where I'm wondering whether I'm leaking memory or not. Let's consider in C++:

bool *test = new bool(false);
test = new bool(true);
delete test;

Am I leaking memory here? Or should I first call delete before assigning a new value? Like this:

bool *test = new bool(false);
delete test;
test = new bool(true);
delete test;

My gut feeling tells me the first is right, as the pointer test points at the same address in memory, and assigning a new value to its variable, will not change this address. Or does the new operator allocate a different address in memory? Can anyone give me a clue, or did I get it wrong all together?

like image 274
Peppivankokki Avatar asked Dec 16 '22 11:12

Peppivankokki


2 Answers

Yes you are leaking, and the c++ way to do it is:

bool test = false;
test = true; 

// ta-da - no leak.

You could do the second approach - however you're likely to draw lots of frowning...

like image 98
Nim Avatar answered Jan 05 '23 16:01

Nim


Yes, exactly, you have to delete before you overwrite the address. Or better yet allocate on stack or use a smart pointer.

like image 40
sharptooth Avatar answered Jan 05 '23 14:01

sharptooth