Memory leak in c

16 Dec 2022 Balmiki Mandal 0 C Programming

What is a Memory leak in c?

A memory leak occurs in C when memory is allocated dynamically using functions like malloc() or calloc(), but the memory is not deallocated when it is no longer needed. As a result, the program uses more and more memory over time, and eventually, the system may run out of memory.

To avoid memory leaks in C, it is important to always free the memory that has been allocated dynamically using functions like free(). It is also a good practice to initialize pointers to NULL when they are declared and to check for NULL before using them.

if we lose the base address of dynamically allocated memory that memory becomes Leake 

Here is an example of a memory leak in C:

int main() {
    int* ptr = (int*)malloc(sizeof(int) * 10);
    ptr = (int*)malloc(sizeof(int) * 20);
    // memory allocated for the first ptr is lost
    return 0;
}

In this example, memory is allocated for ptr twice, but the first allocation is lost because the pointer is reassigned to the second allocation. To avoid this memory leak, the first allocation should be freed before the pointer is reassigned:

 

It is important to note that not all memory leaks are as easy to identify and fix as this example. In large programs, memory leaks can be more difficult to locate and can occur in unexpected ways. Therefore, it is important to be vigilant in managing memory and to use debugging tools to identify and fix memory leaks.

Program:

#include
void main()
{
    char *p;
    p=malloc(10);
    p=malloc(20);
}

In Above Program That 30 Byte memory will be allocated but we are in excess of only 20 bytes here, 10 bytes of memory become leake

Note: What is the Solution

  1. Catch with 2 different pointer
  2. using free function free( ) the first allocated memory then allocate next if you want
  3. The life of a dynamic memory starts when we allocate a memory using malloc and calloc and life ends when we free it or when the program execution is completed 

 

How do we know how many bytes we are free?

 

 

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.