What is Memory Leak? How can we avoid? Last Updated : 16 Sep, 2025 Comments Improve Suggest changes Like Article Like Report Data can be stored in either stack or heap memory. The stack stores local variables and parameters of the function while the heap is used for dynamic memory allocation during runtime.A memory leak occurs when a program dynamically allocates memory but does not release it after it's no longer needed.In C, memory is allocated using malloc() / calloc() and released using free().In C++, memory is allocated using new / new[] and released using delete / delete[].Memory Leak C++ #include <iostream> using namespace std; int main() { // allocate memory int *ptr = new int; *ptr = 20; cout << *ptr << endl; // Forgot to delete memory delete ptr; return 0; } C #include <stdio.h> #include <stdlib.h> int main() { // allocate memory int *ptr = (int *)malloc(sizeof(int)); *ptr = 10; printf("%d\n", *ptr); // Forgot to free memory free(ptr) is missing return 0; } Common Causes of Memory LeakMemory is allocated (malloc/new) but not released (free/delete).If a pointer to allocated memory is overwritten or goes out of scope without freeing, the memory it pointed to becomes unreachable.In long-running programs, even small leaks add up over time. This gradually eats up system memory, making the program slow or crash.How to avoid memory leaks?Always free/ delete the memory after use.Don't overwrite a pointer before freeing its old memory.In C++, prefer smart pointers (unique_ptr, shared_ptr) to handle memory automatically.Use tools like Valgrind to detect leaks during testing. Comment More info K kartik Follow Improve Article Tags : Articles C Language C-Pointers C-Dynamic Memory Allocation Explore C BasicsC Language Introduction6 min readIdentifiers in C3 min readKeywords in C2 min readVariables in C4 min readData Types in C5 min readOperators in C8 min readDecision Making in C (if , if..else, Nested if, if-else-if )7 min readLoops in C6 min readFunctions in C6 min readArrays & StringsArrays in C6 min readStrings in C6 min readPointers and StructuresPointers in C9 min readFunction Pointer in C6 min readUnions in C4 min readEnumeration (or enum) in C5 min readStructure Member Alignment, Padding and Data Packing8 min readMemory ManagementMemory Layout of C Programs5 min readDynamic Memory Allocation in C7 min readWhat is Memory Leak? How can we avoid?2 min readFile & Error HandlingFile Handling in C11 min readRead/Write Structure From/to a File in C3 min readError Handling in C8 min readUsing goto for Exception Handling in C4 min readError Handling During File Operations in C5 min readAdvanced ConceptsVariadic Functions in C5 min readSignals in C language5 min readSocket Programming in C8 min read_Generics Keyword in C3 min readMultithreading in C9 min read Like