×

Memory leak in C

What is memory leak in C?

Memory leak occurs when we keep allocating memory in the heap without freeing it, i.e., the allocated memory in heap is not released back to the heap. The overall memory usage keeps on increasing and reduces the available memory for the program which results in reduction of efficiency or program performance. It may also lead to program crashes.

In order to understand the concept of memory leak, we must be aware of Dynamic Memory Allocation.

Dynamic Memory Allocation

This manual declaration of memory at run time is known as dynamic memory allocation and this is carried by a special set of functions known as library functions. The calloc() is a library function in C which is used for dynamic memory allocation.

The malloc() function also performs the task of memory allocation but the allocated memory is uninitialized.

To summarize, Dynamic Memory Allocation is a way in which the size of a Data Structure can be changed during the runtime.

Note: Memory assigned to a program can be broken down into 4 segments, they are as follows:

  1. Code
  2. Static/ Global variable
  3. Stack
  4. Heap
Heap
Stack
Global/ static variable
Code

Cause of Memory Leak

Memory leak in C can occur due to many reasons, but the prominent reasons for this phenomenon to occur are as follows:

  • It may be caused, when we don’t use dynamic memory properly.
  • When we keep allocating memory in the heap without freeing, i.e., we don't free the memory that is no longer required. This situation is the main cause of memory leak, i.e., the program creates a memory block in memory and forgets to delete it.
  • We try to free the memory but we are not aware of the reference to it (dangling pointer).
  • We try to free the memory using the wrong function.

Note : In order to avoid the situation of memory leak, the memory allocated on heap should always be freed when not required.

Let’s try to understand the concept of memory leak with the help of a C program

Program 1: Memory leak in C

#include <stdio.h>
#include <stdlib.h>


int main()
{
    int x, i = 0;   //declaring the local variables 
    int *p;          //creating a pointer
    while (i< 55565)
    {
       printf("Hello World \n");
       p = malloc(32323 * sizeof(int));  //dynamic memory allocation using malloc()


       /* pointer p points to a heap using a memory block which is 32323 in size */
       if(i%100 == 0) // p comes in multiple of 100
       {
           getchar();   //causes program to stop, i.e our program runs in multiple of 100
       }
       i++;  //incrementing the value of i
    }
    


    return 0;
}

Code explanation:

The program may run smoothly and print desired output, but what actually happens is that every time the program proceeds, i.e., the while loop runs, the memory used by the compiler on the machine will keep on increasing every time the loop executes.

The frequent execution of the code will impact the program performance and it may even cause a program crash.

This is a clear indication of memory leak and it can be resolved by simply using a line of code which frees the memory that is no longer needed.

Program 2: Preventing Memory leak in C

#include <stdio.h>
#include <stdlib.h>


int main()
{
    int x, i = 0;   //declaring the local variables 
    int *p;          //creating a pointer
    while (i< 55565)
    {
       printf("Hello World \n");
       p = malloc(32323 * sizeof(int));  //dynamic memory allocation using malloc()


       /* pointer p points to a heap using a memory block which is 32323 in size */
       if(i%100 == 0) // p comes in multiple of 100
       {
           getchar();   //causes program to stop, i.e our program runs in multiple of 100
       }
       i++;  //incrementing the value of i
       free(p);  //prevents memory leak
    }
    


    return 0;
}

Code explanation:

Using the free() function we are preventing the program from encountering a memory leak. This simple piece of code frees the memory that is no longer needed.

Hence, if we observe the memory usage (in background) after implementing this function, the memory usage will remain the same for every loop count or each iteration of i. This happens because we are clearing the allocated memory that is no longer required.


Related Topics

C vs Java Strings

String in C In C, we can define a string as a bunch of characters. A character array is distinguished from a string by the presence of the special character '\0'...

5 minutes read.

Command line arguments in C

Command line arguments in C The arguments that are generally passed from the line of command are referred to as command line arguments. These command line arguments are always handled by...

3 minutes read.

What is a buffer in C?

A buffer is an area of memory set aside for the temporary storage of data. A data buffer (or just buffer) is a region of a physical memory storage used to...

5 minutes read.

Addition of Matrix in C

The mathematical operation of includingor greater matrices is called the addition of matrices. A matrix is a square series of numbers, symbols, words, letters, and different things. In this article,...

3 minutes read.

Assert() Function in C

Assert (): In C, the statements are executed with the exit statement. In C language declare, and it tests the condition parameters. If the statement executed will be false, it...

3 minutes read.

Binary Search in C with Best and Worst Time Complexity

What is Binary Search? Binary search is an algorithm that is used to find an element in a sorted array efficiently. It has a time complexity of O(log n). It means...

3 minutes read.

C program to find factorial of a number using Recursion

What does the term "Factorial of a Number" mean? In mathematics, factorial is the product of all positive integers that are less than or equal to a certain positive integer, and...

2 minutes read.

Errors in C

Errors in C Errors are nothing but problems or faults that pretty much occur in all the programming languages. Errors make the behavior of the program seem abnormal, and even the...

4 minutes read.

How to use sine() function in C

What is Function? The function is a set of statements. It takes input and performs some computation to produce output. The process is a set of codes only achieved when it is...

3 minutes read.

function pointer as argument in C

Pointers are considered difficult to understand for beginners but pointers can be made to work if you fiddle with them long enough. So, let’s understand this step by step. What are...

3 minutes read.

Memory leak in C

What is memory leak in C? Memory leak occurs when we keep allocating memory in the heap without freeing it, i.e., the allocated memory in heap is not released back to...

3 minutes read.

Remove an element from an array in C

A collection of objects or pieces of the same data type stored in a single memory block is known as an array. A data structure called an array is used...

3 minutes read.

What is algorithm in C?

What is an algorithm? In computer programming languages, an algorithm is set of statement that solves a particular problem. In C, first step of every algorithm is Start and last step of...

3 minutes read.

If else Programs in C Programming

If else Programs in C programming The if-else statement in C is based on some particular conditions to perform the operations. If and only if the given condition is valid, the operations listed in...

4 minutes read.

Continue in C

C language: C language is a procedure oriented programming language. We can say that it is a platform dependent language. C language is introduced by Dennis Ritchie in the year 1970. We...

2 minutes read.

Malloc function in C

When the user or programmer does not know how much memory space is needed in the application, it a needs dynamic memory allocation during runtime. Dynamic memory allocation helps us to...

4 minutes read.

C Program for Mean and Median of an Unsorted Array

In this tutorial, we will look at how to determine the mean and median of a given unsorted array. To determine the Mean: To get the average, mean is determined. The formula...

2 minutes read.

Matrix Multiplication in C

Matrix Multiplication in C Matrix multiplication in C: Two matrices can be added, subtracted, multiplied, and divided. To do so, we take input from the consumer for row number, column number, first element matrix,...

3 minutes read.

Modulus on Negative Numbers in C

In this tutorial, we will explore some examples of modulus on negative number. What is Modulus of Negative number? By omitting the minus sign, one can determine the modulus of a negative...

3 minutes read.

#undef in C

#undef in C In the C programming language, the #undef directive is used to undefine the macro or any constant, which will be defined by the preprocessor directive #define. The #undef...

3 minutes read.