Question: What is a Memory Leak in C?
Answer: In systems, functions ‘malloc()’ and ‘free()’ maintain pool of available memory for use by processes under dynamic requirements. This pool of memory is a limited resource. If a program is allocated memory from this pool and does not free up the chunk when it is no longer needed, this results in a memory leak. This chunk of memory is freed only when program exits.
In situations, where dynamic allocation is no longer required to maintain, free up the chunk before program terminates. There’s no significance of freeing up allocation in the end of program; because, it’d be similar to retain memory till program exits. This is also memory leak!
Memory leak is a severe problem when a program is repeatedly requesting more memory indefinitely and not freeing up any. This will exhaust pool of available memory.
Concept of Memory Leak in C with Example:
/* mem_leak.c -- program displays the concept of memory leak */ #include <stdio.h> #include <stdlib.h> int main(void) { int *pi; int num; puts("**Let's unravel memory leak!**"); printf("User, read in size of block, an integer value, u want to allocate" " memory: "); scanf("%d", &num); /* Let's try to allocate block */ pi = (int *)malloc(num * sizeof(int)); /* confirm if allocation successful */ if (pi == NULL) { puts("System sort of memory!"); exit(1); } /* we are done with the allocation */ /* free up memory here */ /* other statements */ /* if u again required a dynamic block */ /* get that here again */ pi = (int *)malloc(num * sizeof(int)); /* free up when you are done */ return 0; }
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Check C Books
- Check Computer Science Books
- Apply for C Internship
- Apply for Computer Science Internship
- Practice BCA MCQs