Home Misc What is a memory leak?

What is a memory leak?

by nikoo28
0 comments 1 minutes read

Question:What is a memory leak in a program?

We have been writing many programs where we have used the “free()” keyword. One such example can be found in the “Delete the complete list” function found in the post – Important traversals in a Linked List. The code snippet is:-

struct node * deleteList(struct node * head)
{
    struct node * temp;
    while(head != NULL)
    {
        temp = head;
        head = head -> next;
        free(temp);
    }
    return NULL;
}

This is done due to a reason. When we allocate a memory in a program, usually that memory is unallocated once the execution of the program finishes. However, there may be some cases where the program runs forever and these scenarios, we term it as a memory leak. Memory leak occurs when programmers create a memory in heap and forget to delete it. Therefore memory leaks are particularly serious issues for programs like daemons and servers which by definition never terminate.

Here is an example of memory leak:-

void func()
{
    // in the below line we allocate memory
    int *ptr = (int *) malloc(sizeof(int));

    /* Do some work */

    return; // Return without freeing ptr
}
// We returned from the function but the memory remained allocated.
// This wastes memory space.

A correct implementation of the above function to avoid memory leak would be:-

void func()
{
    // We allocate memory in the next line
    int *ptr = (int *) malloc(sizeof(int));

    /* Do some work */

    // We unallocate memory in the next line
    free(ptr);

    return;
}

It is always a good practice to free the allocated memory.

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More