What is Memory Leak in C?

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.

advertisement
advertisement
If you wish to look at all C Tutorials, go to C Tutorials.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.