6

From the discussion started here, I'd like to know whether the following code has a memory leak:

int main()
{
   new int();
   //or
   int* x = new int();
   return 0;
}

I know the memory is reclaimed by the OS, but is it a leak anyway? I believe it is.

What defines a memory leak? I could only find one reference in the standard, and it wasn't very helpful.

EDIT: I don't want to start a debate - "I think that..." is not the kind of answer I'm looking for. I'm mostly interested in sources - what C++ books or websites or whatever have to say about it.

Community
  • 1
  • 1
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • 3
    A memory leak is simply memory you allocate but do not free. – Some programmer dude Mar 29 '12 at 08:23
  • @JoachimPileborg that's what I'm saying in the leaked discussion. James is saying it's a gradual loss of memory. I couldn't find any satisfying sources. – Luchian Grigore Mar 29 '12 at 08:24
  • @Joachim that is too simple. Allocated memory is according to your definition already a memory leak – stefan bachert Mar 29 '12 at 08:27
  • 1
    Re the edit: there's no definitive reference when it comes to the meaning of a word, so "I think that..." is more or less implied in any answer. About the only non-subjective argument that can be applied concerns the usefulness of the proposed definition, and even that isn't 100% objective. – James Kanze Mar 29 '12 at 08:47
  • 2
    Useless discussion. The term "Memory Leak" only has meaning in relation to the context. The most general meaning is dynamically allocated memory that has been lost(there are no references to the memory) to the applications thread(s) of execution and thus can not be usefully utilized. – Martin York Mar 29 '12 at 10:30

6 Answers6

5

It depends on how you define "leak". According to the most obvious definition, and the only useful one, it is not a leak, at least at the application level. A bucket doesn't leak because you intentionally allow a finite quantity of water to escape. And practically speaking, an application doesn't fail because you intentionally allow a bound set of objects to persist beyond the end of the program.

With regards to memory leaks, our perception of the word has been colored by "leak checkers"---programs like Purify or Valgrind. Their role is to find leaks (amongst other things), but they have no way of knowing what is intentional, and what isn't, and what is bound, and what isn't. So they invent other definitions: an object which is unreachable has "leaked" (and there's a good probability in real code that that's true), or an object which hasn't been deleted after all of the destructors of static objects have been executed has "leaked". In this latter case, the definition is obviously wrong, and sort of useless. But there are enough cases where such things are leaks that it is reasonable to at least warn about them ("possible leaks"), provided there is a way of filtering out specific cases. (Both Purify and Valgrind recognize that not all of these cases are really leaks, and provide various filtering mechanisms for their detection.) All of which is well and good—I'm very happy that we have such tools—but we shouldn't allow them to pervert the language.

And one final reminder: the standard says that the standard iostream objects (std::cout, etc.) will never be destructed. So any buffers they allocate will (probably) never be freed. Certainly no one in their right mind would consider these "leaks".

James Kanze
  • 150,581
  • 18
  • 184
  • 329
  • 1
    It is certainly an interesting point of view, I had never thought of the *finite leak* scenario, but it does make sense. I feel enlightened. – Matthieu M. Mar 29 '12 at 08:45
  • @MatthieuM. From a pragmatic point of view, the issue of "boundedness" seems important to me. And it fits with what I intuitively think of as a "leak" in non programming contexts. But checking with Merriam-Webster suggests that even in non programming contexts, it's not that clear. – James Kanze Mar 29 '12 at 08:50
  • The term "leak" can imply both bounded and unbounded scenarios, in programming and non-programming contexts. The fact that only five-gallons of liquid can escape from a hole in a five-gallon bucket doesn't mean the hole is not a "leak". And if objects will continue to exist uselessly after a program exits, they're leaked. On the other hand, if running the program again would cause the objects to be reused, they fact that they're reusable means they're not "useless". And if the OS will clean them up before they cause a problem, they're not leaked. – supercat Nov 29 '12 at 22:33
4

The above code does indeed have a leak. More importantly, however, if instead of allocating an int, you allocated a special object, say a server connection object, if you never properly clean up and call delete, the object's destructor is never run, which might be important if your server connection needs to perform special clean up code (write to files, etc).

In your specific example, the leak is of no consequence since main immediately exits (effectively) and the memory is freed back to the OS. In writing production code, however, you should definitely not leave any leaks (even one as trivial as above) since the code might get moved around into a different function, and the leak could actually propagate itself through the programs lifetime.

Also, perhaps the most important thing to consider is what you the programmer consider to be a memory leak. You should consider memory as a resource that should be managed according to your own model. Consider reading this article which discusses some resource allocation and management models. Consider RAII (resource acquisition is initialization) and smart pointers (or at least the idea of smart pointers and the idea of reference counting).

Community
  • 1
  • 1
Chris
  • 2,786
  • 1
  • 28
  • 31
  • Someone want to fill me in on the -1? – Chris Mar 29 '12 at 08:32
  • Same here. Best for us to know what is wrong with our answers so we can delete/edit them if they are inaccurate. – Alex Z Mar 29 '12 at 08:33
  • There's no reference to what a memory leak means. Doesn't really answer the question. – Luchian Grigore Mar 29 '12 at 08:38
  • You ask explicitly 'I'd like to know whether the following code has a memory leak'. While I've deleted mine because imho the others are better, I think this answer is relevant enough not to justify a downvote. – Alex Z Mar 29 '12 at 08:49
1

I would define a memory leak this way

a) it takes memory

b) it is no more useful for the application

c) it is no more accessible, and therefore no more deleteable

According to this I would judge your sample as memory leak. Your sample show an uncritical leak. A critical leak is continuous taking memory, what could happen until the application crashes

stefan bachert
  • 9,413
  • 4
  • 33
  • 40
1

It is subjective/debatable.

In my opinion there are two levels of resource (memory is one of the resources provided by OS) leaks: OS-level and Application Level. Please note that names are custom and there might be a better suitable technical term for them.

Application-level leak ceases to exist once application terminates because OS cleans application's mess. I.e. once application is nuked, threat to OS stability is gone. On decent operating system memory allocations in applications can only produce "application-level" leak.

OS-level leak will not cease to exist once application terminates. Normally some other resources fall into that category (files), but not memory. However, I cannot guarantee that there is no operating system/platform that doesn't clean up leaked memory. By murphy's law there probably is such platform used even today.

So when I say/write "memory leak" I'm talking about application-level leak - any memory allocation that is not explicitly deleted by APP. Every allocation, even intentional, falls into category. Also, normally memory allocation profilers and similar tools will complain about your "intentional leaks",

So, yes, your code has a leak.

In my opinion, making leaks even on purpose, even when you're certain that OS will free them is a bad idea because it encourages sloppy coding and one day you'll fail to delete class that releases something importan in its destructor that can't be cleaned up by OS automatically. Given amount of junk left in windows registry and temporary files folder on average PC, many programmers routinely use that technique for resources that aren't cleaned up by OS properly. So the best idea would be to avoid making leaks.

SigTerm
  • 26,089
  • 6
  • 66
  • 115
  • If you're talking about resources in general (and not just memory), then OS's aren't capable of cleaning up everything. A temporary file which you fail to delete is a resource leak which will not be cleaned up by the OS. (As for the rest, you've invented a totally new and useless definition of the word "leak".) – James Kanze Mar 29 '12 at 08:44
1

Second case is not a memory leak.
It is not a leak because you still have an pointer to the memory that was allocated.
To define a memory leak I would like to stick to definition which most of memory analysis tools like valgrind use:

Memory was allocated and cannot be subsequently freed because the program no longer has any pointers to the allocated memory block.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • 1
    +1 I sort of knew this, that's why I posted both versions. So the first one is, even though it's not continuously leaking? – Luchian Grigore Mar 29 '12 at 08:37
  • 2
    +1: A short, concise definition: `objects inaccessible by running code but still stored in memory` – Jesse Good Mar 29 '12 at 08:39
  • @LuchianGrigore: I purposefully restrained from commenting on the first scenario because your question says, *"I think that... is not the kind of answer I'm looking for"*. Well, Since you asked, I think the first scenario is a leak, and I am sure valgrind agrees but then again it's only me and valgrind thinking, not some standard :) – Alok Save Mar 29 '12 at 08:40
  • @Als the pointer ceases to exist when he returns from `main`, so that's not an argument one way or the other. – James Kanze Mar 29 '12 at 08:42
  • 4
    I would say the second case is still a leak; main() is not special once main exits there are no references to the dynamically allocated memory anymore (so it has leaked) and the program is still running until it exits to the OS> – Martin York Mar 29 '12 at 10:27
-1

Yes, there is a leak of 4 bytes because memory allocated by new is not deleted and during the life of the application it is a leak.

From this link:

http://www.yolinux.com/TUTORIALS/C++MemoryCorruptionAndMemoryLeaks.html

Memory leak description: Memory is allocated but not released causing an application to consume memory reducing the available memory for other applications and eventually causing the system to page virtual memory to the hard drive slowing the application or crashing the application when than the computer memory resource limits are reached. The system may stop working as these limits are approached.

Sanish
  • 1,699
  • 1
  • 12
  • 21
  • But this - "causing an application to consume memory reducing the available memory for other applications " - doesn't apply. – Luchian Grigore Mar 29 '12 at 08:38
  • If there is an application leaking memory in a loop and this application is running for a longer period of time, the system would slow down. Of course that depends on the amount of memory leaking. The leak in your example will not cause a system to slow down. – Sanish Mar 29 '12 at 08:40
  • Yes, I know there is no loop in your code. I mentioned loop because that is a case where memory leak could slow down system. – Sanish Mar 29 '12 at 08:48