What is memory leak

What is memory leak

Introduction

When a program runs, it needs memory, which is under the control of the operating system. Therefore, after the operating system loading the program into the memory(RAM), the program would also request some extra memory(RAM) from the operating system, then the operating system allocates memory to the program.

It is the duty of the program to release unused memory back to the operating system. Then the freed memory can be allocated to other programs by the operating system. But sometimes a program fails to released back the unused memory. It is still holding the memory but not actually using it. This is called memory leak.

Simple example in C

Memory leak is a common error when using programming languages such as C and C++, which do not have automatic grabage collection. Let’s Take C for example.

Case 1

1
2
3
int *p = (int *)malloc(10);
p = (int *)malloc(20);/* Change the reference
free(p);

Case 2

1
2
3
4
5
6
7
8
void foo() 
{
int *p = (int *) malloc(sizeof(int));

/* Do some work using pointer p */

return; /* return without free p */
}

Explaination of memory leak

To explain the above code, we should know what stack and heap are. There are different areas in computer’s memory, including stack and heap. As shown in the picture, the stack has higher memory addresses and typically has a predefined size around 2 megabytes or so, while the heap has lower memory addresses and a larger size. Another key difference between stack and heap, is that the stack space is automatically allocated and released by the compiler, while the heap space is generally allocated and freed by programmers.

stack_and_heap

In case 1, when we use malloc to request memory, that memory comes from the heap. As shown in the pictur, if we change the reference of p, the memory allocated previously cannot be reused because the reference to it has been lost, and a leak has occured.

memory_leak_case1

In case 2, we also use malloc to request a chunk of memory from heap. When the fuction foo is popped, we lost the reference of the allocated memory, which also causes memory leak. To avoid memory leak, we can modify the code in case 2:

1
2
3
4
5
6
7
8
9
10
void foo() 
{
int *p = (int *) malloc(sizeof(int));

/* Do some work using pointer p */

free(p);

return;
}