Memory leak occurs when programmers create a memory in heap and forget to delete it.
Memory leaks are particularly serious issues for programs like daemons and servers which by definition never terminate.
/* Function with memory leak */#include <stdlib.h> void f() { int *ptr = (int *) malloc(sizeof(int)); /* Do some work */ return; /* Return without freeing ptr*/} |
chevron_right
filter_none
To avoid memory leaks, memory allocated on heap should always be freed when no longer needed.
/* Function without memory leak */#include <stdlib.h>; void f() { int *ptr = (int *) malloc(sizeof(int)); /* Do some work */ free(ptr); return; } |
chevron_right
filter_none
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Memory leak in C++ and How to avoid it?
- What are Wild Pointers? How can we avoid?
- How to avoid Structure Padding in C?
- How will you show memory representation of C variables?
- How does free() know the size of memory to be deallocated?
- Memory Layout of C Programs
- How to deallocate memory without using free() in C?
- fork() and memory shared b/w processes created using it
- C | Dynamic Memory Allocation | Question 1
- C | Dynamic Memory Allocation | Question 2
- C | Dynamic Memory Allocation | Question 3
- C | Dynamic Memory Allocation | Question 8
- C | Dynamic Memory Allocation | Question 5
- C | Dynamic Memory Allocation | Question 6
- C | Dynamic Memory Allocation | Question 7
- C | Dynamic Memory Allocation | Question 8
- POSIX shared-memory API
- Common Memory/Pointer Related bug in C Programs
- MCQ on Memory allocation and compilation process
- IPC through shared memory

