
- C - Home
- C - Overview
- C - Features
- C - History
- C - Standards
- C - Environment Setup
- C - Program Structure
- C - Hello World
- C - Compilation Process
- C - Comments
- C - Basic Syntax
- C - User Input
- C - printf Function
- C - Format Specifiers
- Lexical Elements in C
- C - Tokens
- C - Keywords
- C - Identifiers
- Variables and Constants
- C - Variables
- C - Constants
- C - Const Qualifier
- C - Linkage
- Data Types and Type Conversions
- C - Data Types
- C - Literals
- C - Escape sequences
- C - Booleans
- C - Integer Promotions
- C - Character Arithmetic
- C - Type Conversion
- C - Type Casting
- Operators in C
- C - Operators
- C - Arithmetic Operators
- C - Unary Operators
- C - Relational Operators
- C - Logical Operators
- C - Bitwise Operators
- C - Assignment Operators
- C - Increment and Decrement Operators
- C - Ternary Operator
- C - sizeof Operator
- C - Operator Precedence
- C - Miscellaneous Operators
- Decision Making & Control Statements
- C - Decision Making
- C - if statement
- C - if...else statement
- C - if...else if Ladder
- C - Nested if statements
- C - Switch statement
- C - Nested switch statements
- C - Switch Case Using Range
- Loops in C
- C - Loops
- C - For Loop
- C - While Loop
- C - Do...while Loop
- C - For Loop vs While Loop
- C - Nested Loop
- C - Infinite Loop
- C - Break Statement
- C - Continue Statement
- C - Goto Statement
- Functions in C
- C - Functions
- C - Function Prototype
- C - Main Function
- C - Function call by Value
- C - Function call by reference
- C - Nested Functions
- C - Variadic Functions
- C - User-Defined Functions
- C - Callback Function
- C - Return Statement
- C - Recursion
- C - Predefined Identifier __func__
- Scope Rules in C
- C - Scope Rules
- C - Static Variables
- C - Global Variables
- Arrays in C
- C - Arrays
- C - Properties of Array
- C - Multi-Dimensional Arrays
- C - Passing Arrays to Function
- C - Return Array from Function
- C - Variable Length Arrays
- C - Dynamic Arrays
- Strings in C
- C - Strings
- C - Array of Strings
- C - Character Arrays
- C - Special Characters
- Structures and Unions in C
- C - Structures
- C - Structures and Functions
- C - Arrays of Structures
- C - Self-Referential Structures
- C - Dot (.) Operator
- C - Lookup Tables
- C - Enumeration (or enum)
- C - Structure Padding and Packing
- C - Nested Structures
- C - Anonymous Structure and Union
- C - Unions
- C - Bit Fields
- C - Typedef
- Pointers in C
- C - Pointers
- C - Pointers and Arrays
- C - Applications of Pointers
- C - Pointer Arithmetics
- C - Array of Pointers
- C - Pointer to Pointer
- C - Function Pointers
- C - Array of Function Pointers
- C - Passing Pointers to Functions
- C - Return Pointer from Functions
- C - Pointer to an Array
- C - Pointers vs. Multi-dimensional Arrays
- C - Character Pointers and Functions
- C - NULL Pointer
- C - void Pointer
- C - Const Pointers & Pointer to Const
- C - Dangling Pointers
- C - Dereference Pointer
- C - Near, Far and Huge Pointers
- C - Restrict Keyword
- C - Pointers to Structures
- C - Chain of Pointers
- C - Pointer vs Array
- C - Initialization of Pointer Arrays
- C - Flexible Array Members in Structures
- C - Structures vs Unions
- Storage Classes and Qualifiers
- C - Storage Classes
- Memory Management in C
- C - Memory Layout
- C - Memory Management
- C - Memory Address
- C - Memory Leaks
- Preprocessors in C
- C - Preprocessors
- C - Pragmas
- C - Preprocessor Operators
- File Handling in C
- C - File I/O (File Handling)
- C - Input & Output
- Constants and Literals in C
- C - Macros
- C - Header Files
- Miscellaneous Topics
- C - Error Handling
- C - Variable Arguments
- C - Command Execution
- C - Math Functions
- C - Static Keyword
- C - Random Number Generation
- C - Command Line Arguments
- C Programming Resources
- C - Questions & Answers
- C - Quick Guide
- C - Cheat Sheet
- C - Useful Resources
- C - Discussion
- C Online Compiler
Memory Leaks in C
Memory leaks take place when the memory allocated to variables is not deallocated after their use. The allocated memory is no longer in use by the program, but the space remains reserved for no reason. That's why it is called a memory leak.
In a memory leak, some blocks of memory may be wasted. Memory leaks can slow down the system performance, even when the system has enough memory.
In C programming, memory is allocated using the malloc() / calloc() methods and released using the free() method. Let us understand by example how memory leaks occur −
Example: Memory Leak in C
In this example, we are allocating the size of the variable but not deallocating the space after its use, so it may cause a memory leak −
#include <stdio.h> #include <stdlib.h> int main(){ // allocate memory int *ptr = (int *)malloc(sizeof(int)); *ptr = 100; printf("%d\n", *ptr); // we are just allocating the memory // not deallocating return 0; }
The code will work as expected, but without freeing the allocated memory, it causes a memory leak. Given below is the output of the code −
100
Causes of Memory Leaks
C allows programmers to allocate memory during program execution using functions from the stdlib.h library, such as malloc() (allocate a block of memory), calloc() (allocate zero-initialized memory), and realloc() (resize an allocated block). This memory is allocated on the heap. If the allocated memory is not released when no longer needed, it remains reserved unnecessarily, even after the program has finished using it.
Following are the prime causes that can result in memory leaks −
- Memory is allocated but not released or deallocated.
- If a pointer to allocated memory is overwritten or goes out of scope without being freed, the memory it points to becomes unreachable.
- In long-running programs, even small memory leaks can accumulate over time, gradually consuming system memory and eventually slowing down or crashing the program.
Example: Memory Leak in C Using calloc()
In this example, we are allocating memory using the calloc() function, but we are not freeing the memory, which causes a memory leak −
#include <stdio.h> #include <stdlib.h> int main() { int *ptr; // Allocate memory for 5 integers using calloc ptr = (int *)calloc(5, sizeof(int)); if (ptr == NULL) { printf("Memory allocation failed.\n"); return 1; } // Use the allocated memory for (int i = 0; i < 5; i++) { ptr[i] = i + 1; printf("%d ", ptr[i]); } printf("\n"); // This line is intentionally commented to // create a memory leak // free(ptr); return 0; }
When you run this code, it will produce the following output −
1 2 3 4 5
How to Prevent Memory Leaks
Following are the ways to prevent memory leaks −
- Always free/deallocate the memory after use.
- Do not overwrite the pointer before freeing its old memory.
- Unlike C++, C does not have smart pointers, so memory must be explicitly freed using the free() function.
- We can use tools like Valgrind in C to detect memory leaks during testing.
To prevent memory leaks, we use the free() function. It deallocates the allocated memory and helps avoid memory leaks.
Example: Preventing Memory Leaks
In this example, we use the free() function to prevent memory leak −
#include <stdio.h> #include <stdlib.h> int main(){ // allocate memory int *ptr = (int *)malloc(sizeof(int)); *ptr = 100; printf("%d\n", *ptr); // free allocated memory free(ptr); return 0; }
Following is the output of the above code −
100
Conclusion
Memory leaks take place when a program allocates memory to its variables and fuctions but does not free/deallocate the memory after its use. Over time, unused memory occupies space and becomes wasted, which can slow down the program or even cause it to crash. Proper memory management is important to prevent these issues.