9

what are the reasons for memory leakage in C C++ (except the usual allocating memory and forget to deallocate it)

ashmish2
  • 2,885
  • 8
  • 40
  • 54

8 Answers8

20

If an exception is raised between allocation and deallocation, memory leak will occur.

void f1() {
    int* ptr = new int;

    // do something which may throw an exception

    // we never get here if an exception is thrown
    delete ptr;
}

Each time f1 terminates with an exception, 4 bytes are leaked (assuming int is 4 byte).

watson1180
  • 2,015
  • 1
  • 18
  • 24
  • 3
    ...one of the reasons that smart pointers are "smarter" than raw pointers like `int *` (which have no destructor): http://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one – HostileFork says dont trust SE Dec 15 '10 at 08:58
15

A memory leak is caused when you allocated memory, haven't yet deallocated it, and you will never be able to deallocate it because you can't access it anymore.

For example, the following code causes a memory leak of size sizeof(int):

int * a = malloc(sizeof(int)); //allocate memory
a = 0; //this will cause a memory leak

This creates a memory leak, because now we will never be able to deallocate the memory allocated for a.

Cam
  • 14,930
  • 16
  • 77
  • 128
6

You can also leak memory when you don't deallocate some other resource like not calling fclose on a FILE* or some other library handle because they can allocate buffers of memory that aren't directly accessible to your program.

ldav1s
  • 15,885
  • 2
  • 53
  • 56
5

Let's say you have created a class that inherits some other class that doesn't have a virtual destructor. If the type of the pointer to this class isn't the most derived class (this usually happens if you use an abstract factory) then only the destructor from the pointer's type will be called and anything you had been hoping do free in the most derived class destructor will leak.

This is a very common error and one that some times is hard to see.

Anyway, if you want to avoid memory leaks with C++ follow this rules:

  • Prefer passing references rather than pointers
  • Use smart pointer whenever possible (see: shared_ptr)
Raphael
  • 7,972
  • 14
  • 62
  • 83
  • of course, the standard says it's undefined behavior if the destructor of the base class is not virtual, so you're tampering with evil and a memory leak is the least of your worry here. As for `shared_ptr`, it's sometimes useful, but there are much better smart pointers / containers out there for daily use. It certainly should be the last choice. – Matthieu M. Dec 15 '10 at 09:32
2

A new without a delete, a new[] without a delete[], a malloc without a free.

Seriously, what else do you want to hear?

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
2

There is no other reason for memory leakage besides the one you mention

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
andreabedini
  • 1,295
  • 1
  • 13
  • 20
  • A counterexample to this is watson1180's answer. – Cam Dec 15 '10 at 07:10
  • @Cam: I don't think so, in watson1180's example, he forgot to call `delete` (even though it's written down in the code). – Matthieu M. Dec 15 '10 at 08:37
  • @Matthieu: Hmm... indeed. Sadly I'm currently unable to un-downvote beb0's answer. – Cam Dec 15 '10 at 08:39
  • @Cam: I've added a capital letter to "There" that should allow you to change your vote :) – Matthieu M. Dec 15 '10 at 08:54
  • Actually there are a lot of reasons for memory leakage – Raphael Dec 15 '10 at 08:56
  • @Raphael: Right, but I think beb0's point is that they all fall under the general category of forgetting to free memory. – Cam Dec 15 '10 at 09:07
  • But his statement implies that memory leak is not an insidious phenomenon when it is, specially when you're dealing with functions that return pointers, exceptions, inheritance, etc. There are lots of possible scenarios for memory leak and some does not involve the programmer explicitly forgetting to free his resources. – Raphael Dec 15 '10 at 09:18
  • @Raphael: how do you explicitly forget something? – JeremyP Dec 15 '10 at 09:36
  • Just like in Cam's answer. In that case it should be obvious to the programmer the need to free the allocated memory be for some reason the programmer forgot to free it (it happens even with the best programmers). – Raphael Dec 15 '10 at 10:06
  • 1
    On the other hand there are some very poorly constructed and poorly documented APIs that you don't know when it is your responsibility to free some resources (hence it's always preferable to return a smart pointer than a raw pointer from a function) – Raphael Dec 15 '10 at 10:09
  • @beb0s +1 for the conceptual punctiliousness as any resource leak eventually boils down to memory allocation and de-allocation. Practically, however, there is a difference between memory that a programmer controls directly (e.g. new/delete, malloc/free) and memory that is allocated and managed indirectly, like Windows resources (icons, cursors, controls, etc.). – Android Eve Dec 15 '10 at 16:16
  • wow. so, yeah I understood "to forget" as "you should have done it but you haven't", therefore it included forgetting that the program can take a different path (due to an exception for example). the same can be said about resource leaks but the op's question was specific to leaking memory. – andreabedini Dec 18 '10 at 01:53
1

I'm surprised nobody mentioned memory corruption yet.

I remember a case when we had a crude fixed-size blocks memory allocator implemented as a linked list.

Some guy had messed up size computations, leading to copy data just a couple of bytes beyond the max block size (pointers were only 2 bytes long at the time :)). It would then overwrite the "next" link located at the begining of the next free block with garbage that happened to be filled with zeroes.

This had the consequence of severing the free blocks chain. Since at that point the other pieces of software maintained their own pointers to whatever blocks they were using, the progam seemed to run just fine.

But of course the list went short of a few blocks once in a while, and this leakage eventually exhausted the free blocks, starving the application to death.

kuroi neko
  • 8,479
  • 1
  • 19
  • 43
0

The following example, written in pseudocode, is intended to show how a memory leak can come about, and its effects, without needing any programming knowledge. The program in this case is part of some very simple software designed to control an elevator. This part of the program is run whenever anyone inside the elevator presses the button for a floor.

When a button is pressed:

  Get some memory, which will be used to remember the floor number
  Put the floor number into the memory
  Are we already on the target floor?
    If so, we have nothing to do: finished
    Otherwise:
      Wait until the lift is idle
      Go to the required floor
      Release the memory we used to remember the floor number

The memory leak would occur if the floor number requested is the same floor that the lift is on; the condition for releasing the memory would be skipped. Each time this case occurs, more memory is leaked.

mmohab
  • 2,303
  • 4
  • 27
  • 43
mohan
  • 1