Thursday, 28 December 2017

what is the difference between memory leak & memory wastage

what is the difference between memory leak & memory wastage


Memory leak

   Programmers create a memory in heap and forget to delete it and don't have any variable to track the memory, so that in future if we want to delete the memory in code that is not possible this is call memory leak.

Memory wastage:

    User created the memory and forget to delete it but he has the variable to track the memory then that is called the wastage of memory not an leak.

Example:

#include <stdio.h>
#include <stdlib.h>
char *buffer = NULL;
void fun()
{
    char *ptr = NULL;
    if(buffer == NULL) {
        ptr = (char *) malloc(128);
        buffer = ptr;
    }
    else {
        ptr = buffer;
    }
    printf("Vel Enter the details: ");
    scanf("%s", ptr);
    printf("Vel Entered value is = (%s) \n\n", ptr);
    //  we don't need the global variable to track for this program, so we can free this here or we can use local variable instead of heap memory.
    return; /* Return without freeing ptr*/
}

int  main()
{
    fun();
    while(1) {
        /* Added this while to make sure that the process is still running but we could not
           free the memory once come out from the fun().  */
        sleep(1);
    }
    // here or some where  in the program we need to free the buffer if it is not used,
    // we are not using the buffer  anymore and still tracking the memory using variable then that is not an leak, that is an wastage of memory, programmer not handled the memory efficiently.
    return 0;
}


No comments:

Post a Comment