What is Memory Leak

Memory Leak is a very severe issue and can lead to system performance issues and even to a system crash. Therefore it is very crucial that memory leaks are detected as early as possible in the dynamic analysis and be included in the performance testing.

Memory leak

As you all know when you store items in a warehouse we normally remove the expired items and store the new items in the warehouse. If not we don’t have space to store new Items. Like this in computer science, memory leak occurs when a computer program incorrectly manages memory allocations in such a way that memory which is no longer needed is not released.

Example :

int main (){

double* quantity = new double;

*quantity = 1000;

……..

delete quantity;

return 0;

}

In the following example we are creating a variable called quantity which allocates 8 bytes of memory in the main memory. After using this variable we have to remove that 8 bytes of memory from the main memory. If not, the memory leak will occur.

A memory leak may also happen when an object is stored in memory but cannot be accessed by the running code.

Before we look at memory leaks in different programming languages, it is good to know the architecture of memory, the way the operating system manages the memory and the way memory is accessible to us as programmers.

Here we have explained the concept of dynamic memory and how to work with dynamic memory using C and C++.

Why is it important to detect memory leaks

How to detect memory leaks

Unfortunately memory leaks cannot be detected by tests scripts.

Dynamic Analysis

Examples

Java

C#

Python

C++

Memory Architecture

The memory that is assigned to a program or application in a typical architecture can be divided into four segments as follows :

Local variables are declared inside a function and they live only till the time the function is executing.

The amount of memory set aside for these three segments : the text, global variable and stack does not grow while the application is running.

Example

#include<stdio.h>

int total;

int Square(int x)

{

return x*x;

}

int SquareOfSum(int x, int y)

{

int z = Square(x+y);

return z;

}

int main()

{

int a = 5, b = 8;

total = SquareOfSum(a,b);

printf(“output = %d”, total);

}

Function calls and local variables will be stored in the stack as stated in the following example.

At any time during the execution of the program, the function at top of the stack will execute and rest will be kind of paused, waiting for the function above to return something and then it will resume execution.

This program may not be the best way to implement this logic. When our program starts, our operating system allocates some amount of reserved space, let’s say OS allocates 1MB of space as stack, but the actual allocation of the stack frame and the actual allocation of the local variables happens from the stack during runtime and if our call stack grows beyond the reserved memory for the stack like for example, if a method A calls B, B calls C and we go on calling and we exhaust the whole space reserved for the stack, then this is called stack overflow and in this case our program will crash.

As you can see, there are some limitations of stack. The memory set aside for stack does not grow during runtime. Application cannot request more memory for stack. So if it is 1 MB, then if the allocation of variables and functions in stack exceeds 1 MB, our program will crash.

Further the allocation and deallocation of memory onto the stack happen by a set rule. When a function is called, it is pushed onto the stack, when it finishes, it is popped out of the stack or removed from the stack. It is not possible to manipulate the scope of a variable if it is on the stack.

Stacks are a type of container with Last In First Out(LIFO) principle. In stacks, the elements which are inserted initially are taken out from the stack at last.

Another limitation is that if we need to declare a large data type, like an array as a local variable, then we need to know the size of the array at compile time only. If we have a scenario like we have to decide how large the array will be based on some parameter during runtime then it is a problem with stack. For all those problems, like allocating large chunks of memory or keeping variables in the memory till the time we want, we have a heap.

Unlike stack, the application’s heap is not fixed. It’s size can vary during the lifetime of the application and there is no set rule for allocation or deallocation of the memory. A programmer can totally control how much memory to use from the heap, till what time to keep the data in the memory during the application’s lifetime and heap can grow as long as you do not run out of memory on the system itself. Heap is one large free pool of memory available to us that we can use flexibly as per our need. Heap is also called dynamic memory and using the heap is referred to as dynamic memory allocation.

Memory Leak in C

In C allocating blocks of memory has been done using three functions such as malloc, calloc and realloc. Deallocation of memory has been done using a free function.

Void *p = malloc (4)

Print p //203

It is not the actual code it is just for an example

Below you can see the actual scenario.

Example

#include<stdio.h>

#include<stdlib.h>

int main()

{

int a; // goes on stack

int *p;

p = (int*)malloc(sizeof(int));

*p = 10;

p = (int*)malloc(sizeof(int));

*p = 20;

}

In the following example after writing 10 in this particular block, make one more call to malloc. When we make one more call to malloc, one more block of 4 bytes is allocated on the heap and let us say the address is 400 for this block. Now, the address that is returned by the second call to malloc, we store this address in the variable p. So, what happens is, that p is now pointing to the address 400. We allocated one more block and we modified the address in p to point to this block. The previous block still sits in the heap; it will not be cleared automatically. When we allocate the memory we need to deallocate the memory. So, we use the free function to deallocate the memory.

#include<stdio.h>

#include<stdlib.h>

int main()

{ int a; // goes on stack

int *p;

p = (int*)malloc(sizeof(int));

*p = 10;

free(p); // deallocation

p = (int*)malloc(sizeof(int));

*p = 20;

}

Calloc also returns a void pointer but calloc takes 2 arguments. The first argument is the number of elements of a particular data type and the second argument is the size of the data type.

So, with malloc, if we have to declare an array of size 3, an integer array of size 3, we would say (3*sizeof(int)).

In calloc we would say

int *p = (int*)calloc(3,sizeof(int));

Memory Leak in C++

#include<stdio.h>

#include<stdlib.h>

int main()

{

int a; // goes on stack

int *p;

p = new int; // allocation

*p = 10;

delete p; // deallocation

p = new int[20];

delete [] p;

}

In C++ new memory is allocated by a new operator and deallocate the memory by the delete or delete [] operator. The delete operator should be used to free a single allocated class or data value, whereas the delete [] operator should be used to free an array of data values.

Memory Leak in Java

Unlike C and C++, java has a core benefit of automated memory management with the help of built-in Garbage Collector. It handles the majority of memory leaks issues. But there are some types of memory leak which cannot be handled by GC.

Types of Memory Leaks in Java

Memory Leak Through static Fields

Heavy use of static variables can cause a potential memory leak.

public class StaticTest {

public static List<Double> list = new ArrayList<>();

public void populateList() {

for (int i = 0; i < 10000000; i++) {

list.add(Math.random());

}

Log.info(“Debug Point 2”);

}

public static void main(String[] args) {

Log.info(“Debug Point 1”);

new StaticTest().populateList();

Log.info(“Debug Point 3”);

}

}

Here you can see, when we create a List as a static variable the heap memory will increase. But when we leave the populateList() method the heap memory isn’t yet garbage collected. Inorder to prevent this minimize the use of static variables.

--

--

--

Software Tester

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How To Use Shopify Filter Search Results By Tag

Filter Search Results in shopify

Get started with platform CI/CD Jenkins-Nexus- Gitlab PART I

How to Paint Like Piet Mondrian with Python

What is GitOps?

Web Scraping Instagram with Selenium

Console Roundup: What’s New?

How to track PostgreSQL queries using EntityFramework Core in Application Insights

Road Map to competitive programming

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dayana Loydd

Dayana Loydd

Software Tester

More from Medium

Behind the code: Paulo Gaspar, Director of Engineering, PandaDoc

The Application Non-Functional Requirements Bootcamp — Part One

10 Tips to Help Your Product x Engineering team SHIP 🛳

Microservice, My Mistake In Designing A Web Service