The Wayback Machine - https://web.archive.org/web/20241128223859/https://www.geeksforgeeks.org/what-is-memory-leak-how-can-we-avoid/
Open In App

What is Memory Leak? How can we avoid?

Last Updated : 21 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A memory leak occurs when programmers create a memory in a heap and forget to delete it.

The consequence of the memory leak is that it reduces the performance of the computer by reducing the amount of available memory. Eventually, in the worst case, too much of the available memory may become allocated, all or part of the system or device stops working correctly, the application fails, or the system slows down vastly.

Memory leaks are particularly serious issues for programs like daemons and servers which by definition never terminate.

Example of Memory Leak

The below example shows the memory leak concept.

C
/* Function with memory leak */
#include <stdlib.h>

void f()
{
    int* ptr = (int*)malloc(sizeof(int));

    /* Do some work */

    /* Return without freeing ptr*/
    return;
}

Causes of Memory Leaks in C

  1. When dynamically allocated memory is not freed up by calling free then it leads to memory leaks. Always make sure that for every dynamic memory allocation using malloc or calloc, there is a corresponding free call.
  2. When track of pointers that references to the allocated memory is lost then it may happen that memory is not freed up. Hence keep the track of all pointers and make ensure that memory is freed.
  3. When the program terminates abruptly and the allocated memory is not freed or if any part of code prevents the call of free then memory leaks may happen.

To learn how to avoid memory leaks and manage memory safely in C programs, the C Programming Course Online with Data Structures covers memory management techniques and best practices.

How to avoid memory leaks?

To avoid memory leaks, memory allocated on the heap should always be freed when no longer needed.

Example: Program to Release Memory Allocated in Heap to Avoid Memory Leak

The below program shows the memory allocated in the heap is released to avoid memory leak.

C
/* Function without memory leak */
#include <stdlib.h>

void f()
{
    int* ptr = (int*)malloc(sizeof(int));

    /* Do some work */

    /* Memory allocated by malloc is released */
    free(ptr);
    return;
}

Example: Program to Check Whether the Memory is Freed or Not

The below example demonstrates how to check if the memory allocated on the heap is freed or not.

C
// C Program to check whether the memory is
// freed or not

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

int main(void)
{
    int* ptr;
    ptr = (int*)malloc(sizeof(int));

    if (ptr == NULL)
        printf("Memory Is Insuffficient\n");
    else {
        free(ptr);
        printf("Memory Freed\n");
    }
}
// This code is contributed by sarajadhav12052009

Output
Memory Freed

Conclusion

In conclusion, memory leaks can occur when we allocate memory on the heap but forget to release it or free it. Due to memory leaks, we may experience performance degradation and system becomes unstable. Memory leaks cause more damage for long-running programs like servers. To avoid memory leaks we must free dynamically allocated memory by calling functions like free().


Previous Article
Next Article

Similar Reads

Memory leak in C++ and How to avoid it?
Memory leakage occurs in C++ when programmers dynamically allocate memory by using new keyword (or malloc, calloc) and forgets to deallocate the memory by using delete or delete[] operator (or free). In this article, we will learn about why memory leak occurs in C++ and best practices to avoid it. Why memory leak occurs in C++?In C++, there is no a
4 min read
What are Wild Pointers? How can we avoid?
Uninitialized pointers are known as wild pointers because they point to some arbitrary memory location and may cause a program to crash or behave unexpectedly. Example of Wild PointersIn the below code, p is a wild pointer. C/C++ Code // C program that demonstrated wild pointers int main() { /* wild pointer */ int* p; /* Some unknown memory locatio
2 min read
How will you show memory representation of C variables?
Write a C program to show memory representation of C variables like int, float, pointer, etc. Algorithm: Get the address and size of the variable. Typecast the address to char pointer. Now loop for size of the variable and print the value at the typecasted pointer.Program: C/C++ Code #include &lt;stdio.h&gt; typedef unsigned char *byte_poin
1 min read
C | Dynamic Memory Allocation | Question 1
The most appropriate matching for the following pairs (GATE CS 2000) X: m=malloc(5); m= NULL;        1: using dangling pointers Y: free(n); n->value=5;         2: using uninitialized pointers Z: char *p; *p = ’a’;           3. lost memory is: (A) X—1 Y—3 Z-2 (B) (X—2 Y—1 Z-3 (C) X—3 Y—2 Z-1 (D) X—3 Y—1 Z-2 Answer: (D) Explanation: X -> A poin
1 min read
C | Dynamic Memory Allocation | Question 2
Consider the following three C functions : [PI] int * g (void) { int x= 10; return (&x); } [P2] int * g (void) { int * px; *px= 10; return px; } [P3] int *g (void) { int *px; px = (int *) malloc (sizeof(int)); *px= 10; return px; } Which of the above three functions are likely to cause problems with pointers? (GATE 2001) (A) Only P3 (B) Only P1
1 min read
C | Dynamic Memory Allocation | Question 3
Output? C/C++ Code # include # include void fun(int *a) { a = (int*)malloc(sizeof(int)); } int main() { int *p; fun(p); *p = 6; printf(\"%d",*p); return(0); } (A) May not work (B) Works and prints 6 Answer: (A)Explanation: The program is not valid. Try replacing “int *p;” with “int *p = NULL;” and it will try to dereference a null pointer. This is
1 min read
C | Dynamic Memory Allocation | Question 8
Which of the following is/are true (A) calloc() allocates the memory and also initializes the allocates memory to zero, while memory allocated using malloc() has uninitialized data. (B) malloc() and memset() can be used to get the same effect as calloc(). (C) calloc() takes two arguments, but malloc takes only 1 argument. (D) Both malloc() and call
1 min read
C | Dynamic Memory Allocation | Question 5
What is the return type of malloc() or calloc() (A) void * (B) Pointer of allocated memory type (C) void ** (D) int * Answer: (A) Explanation: malloc() and calloc() return void *. We may get warning in C if we don't type cast the return type to appropriate pointer. Quiz of this Question
1 min read
C | Dynamic Memory Allocation | Question 6
Which of the following is true? (A) "ptr = calloc(m, n)" is equivalent to following ptr = malloc(m * n); (B) "ptr = calloc(m, n)" is equivalent to following ptr = malloc(m * n); memset(ptr, 0, m * n); (C) "ptr = calloc(m, n)" is equivalent to following ptr = malloc(m); memset(ptr, 0, m); (D) "ptr = calloc(m, n)" is equivalent to following ptr = mal
1 min read
C | Dynamic Memory Allocation | Question 7
What is the problem with following code? #include<stdio.h> int main() { int *p = (int *)malloc(sizeof(int)); p = NULL; free(p); } (A) Compiler Error: free can't be applied on NULL pointer (B) Memory Leak (C) Dangling Pointer (D) The program may crash as free() is called for NULL pointer. Answer: (B) Explanation: free() can be called for NULL
1 min read
C | Dynamic Memory Allocation | Question 8
Consider the following program, where are i, j and k are stored in memory? int i; int main() { int j; int *k = (int *) malloc (sizeof(int)); } (A) i, j and *k are stored in stack segment (B) i and j are stored in stack segment. *k is stored on heap. (C) i is stored in BSS part of data segment, j is stored in stack segment. *k is stored on heap. (D)
1 min read
Common Memory/Pointer Related bug in C Programs
Dereferencing an unknown memory location : C programmers mostly use scanf() function to take input, but sometimes a small mistake can bring a bug or even crash whole program. The syntax for scanf() is scanf("%d", &a);. It might be possible to miss a & and write &a as a so now scanf("%d", a); is dereferencing to an unknown location. Now
6 min read
what happens when you don't free memory after using malloc()
Pre-requisite: Dynamic memory allocation in CThe "malloc" or "memory allocation" method is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It initializes each block with a default garbage value.Syntax: ptr = (cast-type*) malloc(byte-
3 min read
If memory allocation using new is failed in C++ then how it should be handled?
In this article, if memory allocation using new is failed in C++ then how it should be handled? When an object of a class is created dynamically using new operator, the object occupies memory in the heap. Below are the major thing that must be keep in mind: What if sufficient memory is not available in the heap memory, and how it should be handled?
3 min read
Random Number Memory Game in C
In this article, will design a simple number memory game in the C programming language. It is a simple memory number game where a random number is displayed and is hidden after some time. The task is to guess that displayed number to continue the game. How to Play This Game: Press 1 on your keyboard to start the game.A random positive number is dis
2 min read
How does C allocate memory of data items in a multidimensional array?
The data items in a multidimensional array are stored in the form of rows and columns. Also, the memory allocated for the multidimensional array is contiguous. So the elements in multidimensional arrays can be stored in linear storage using two methods i.e., row-major order or column-major order. Row major order: In row-major order, we store the el
4 min read
How does free() know the size of memory to be deallocated?
Consider the following prototype of free() function which is used to free memory allocated using malloc() or calloc() or realloc(). void free(void *ptr); Note that the free function does not accept size as a parameter. How does free() function know how much memory to free given just a pointer? Following is the most common way to store size of memor
1 min read
How to deallocate memory without using free() in C?
Question: How to deallocate dynamically allocate memory without using “free()” function. Solution: Standard library function realloc() can be used to deallocate previously allocated memory. Below is function declaration of "realloc()" from "stdlib.h" C/C++ Code void *realloc(void *ptr, size_t size); If "size" is zero, then call to realloc is equiva
2 min read
POSIX shared-memory API
Several IPC mechanisms are available for POSIX systems, including shared memory and message passing. Here, we explore the POSIX API for shared memory. POSIX shared memory is organized using memory-mapped files, which associate the region of shared memory with a file. A process must first create a shared-memory object using the shm_open() system cal
4 min read
MCQ on Memory allocation and compilation process
1. What will be the output of the following code? C/C++ Code #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main() { union test { int i; float f; char c; }; union test* t; t = (union test*)malloc(sizeof(union test)); t-&gt;f = 20.60f; printf(&quot;%f&quot;, t-&gt;f); return 0; } (a) Garbage value (b) 20.60000
3 min read
fork() and memory shared b/w processes created using it
Prerequisite: fork() in C So when we do a fork() what are the sections the two process actually share? Is the heap memory per process? Are the global variables shared? Will malloc return the same address to both? Let us run the program below and take a look at the output of it to clear the questions above. C/C++ Code // C program to demonstrate wor
4 min read
Deleting Memory in C
In C programming, we might allocate memory dynamically for various tasks but what happens when those pieces of memory are no longer needed? If not managed properly, they can lead to memory leaks, wasting valuable resources, and slowing down our program. Therefore, we need to manage memory in C by properly deallocating it when it's no longer in use
5 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations. As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example, If there is a
9 min read
Difference between Static and Dynamic Memory Allocation in C
Memory Allocation: Memory allocation is a process by which computer programs and services are assigned with physical or virtual memory space. The memory allocation is done either before or at the time of program execution. There are two types of memory allocations: Compile-time or Static Memory AllocationRun-time or Dynamic Memory AllocationStatic
3 min read
IPC through shared memory
Inter-Process Communication (IPC) is a fundamental concept in operating systems that allows multiple processes to communicate and synchronize their actions. Among the various methods of IPC shared memory is one of the most efficient mechanisms especially when it comes to performance-critical applications. This article delves into the concept of IPC
7 min read
Memory Layout of C Programs
A typical memory representation of a C program consists of the following sections. Text segment (i.e. instructions)Initialized data segment Uninitialized data segment (bss)Heap Stack A typical memory layout of a running process 1. Text Segment: A text segment, also known as a code segment or simply as text, is one of the sections of a program's mem
6 min read
How can I return multiple values from a function?
We all know that a function in C can return only one value. So how do we achieve the purpose of returning multiple values. Well, first take a look at the declaration of a function. int foo(int arg1, int arg2); So we can notice here that our interface to the function is through arguments and return value only. (Unless we talk about modifying the glo
2 min read
Can We Call an Undeclared Function in C++?
Calling an undeclared function is a poor style in C (See this) and illegal in C++and so is passing arguments to a function using a declaration that doesn't list argument types.If we call an undeclared function in C and compile it, it works without any error. But, if we call an undeclared function in C++, it doesn't compile and generates errors. In
2 min read
Can We Use Function on Left Side of an Expression in C and C++?
In C, it is not possible to have function names on the left side of an expression, but it's possible in C++. How can we use the function on the left side of an expression in C++? In C++, only the functions which return some reference variables can be used on the left side of an expression. The reference works in a similar way to pointers, so whenev
1 min read
Can Global Variables be dangerous ?
In a small code, we can track values of global variables. But if the code size grows, they make code less understandable (hence less maintainable). It becomes difficult to track which function modified the value and how. C/C++ Code // A C++ program to demonstrate that a // global variables make long code less // maintainable. int c = 1; int fun1()
2 min read
three90RightbarBannerImg