Why would this cause a memory leak?

Mar 2, 2012 at 1:02am
Any ideas as to why the following code would cause A memory leak?
1
2
3
4
5
6
7
8
9
10
11
12
bool function();

int main()
{
    while(1)
        function();
}

bool function()
{
    return new bool;
}
Last edited on Mar 2, 2012 at 1:04am
Mar 2, 2012 at 1:04am
No idea... Do you know?

That really shouldn't compile, you spelled "while" wrong
Last edited on Mar 2, 2012 at 1:07am
Mar 2, 2012 at 1:10am
closed account (zb0S216C)
ModShop + 1 for a sarky remark :) To be fair, the cause is just outrageously obvious.

Wazzak
Mar 2, 2012 at 1:18am
closed account (3hM2Nwbp)
It's because new is called, but never delete

I edited my first response in the event that this is a serious question.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <memory>

std::shared_ptr<bool> function(void);

int main(void)
{
  while(true)
  {
    function();
  }
}

std::shared_ptr<bool> function(void)
{
  return std::shared_ptr<bool>(new bool);
}


There I've fixed your memory leak.
Last edited on Mar 2, 2012 at 1:34am
Mar 3, 2012 at 5:15pm
@Luc Lieber:

line 3: error: expected constructor, destructor or type conversion before '<' token.
line 13: error: ditto.

Mar 3, 2012 at 5:22pm
closed account (3hM2Nwbp)
Forgot the disclaimer, that code requires a C++11 compatible compiler.
Mar 3, 2012 at 5:28pm
@Everybody

I meant this post as a half tongue-in-cheek joke, although this was actual code of mine that I wrote once upon a time that I just now found while debugging.

Fortunately I did not waste much time trying to find the culprit, however I only found it by chance, debugging another error when I was glancing at the code in a header file it popped right out at me.

I imagine it would have cost me much grief otherwise.

Funny thing, I remember writing the code in question.

It had to do with having written a function declared as bool, which probably would have been better off left as void. But when I realized that I wasn't returning a value in a bool function, I was too lazy to go back and change the declaration (which was declared at the top of the file.... how lazy am I?) so I decided to return a random bool value, because I felt it would have been akward to return a constant value in a context which would have had no meaning anyway.

Well in retrospect, I should have at least returned a true, as it was expected that the function would have never failed. But I had no easy way to test success so again, this would have 'felt' akward.

So you ask, how did I wind up returning a new bool pointer?

If I recall, it wouldn't let me compile:
1
2
3
4
bool function()
{
     return bool new_var, new_var;
}


so return new bool; was the most concise code I could come up with, and it seemed to work at the time.



Happens to the best of us. C'mon all, admit it.
Topic archived. No new replies allowed.