What is Memory Leak? How can we avoid?
Memory leak occurs when programmers create a memory in heap and forget to delete it.If we dont have any variable to track that memory.
Example : Memory Leak:
#include <stdio.h>
#include <stdlib.h>
void fun()
{
char *ptr = (char *) malloc(128);
printf("Vel Enter the details: ");
scanf("%s", ptr);
printf("Vel Entered value is = (%s) \n\n", ptr);
// we dont have any variable to track that 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 forget to
free the memory once come out from the fun() and dont have variable to track that memroy. */
sleep(1);
}
return 0;
}
How to avoid memory leak:
Memory allocated on heap should always be freed(using free() call) when no longer needed.Example :
#include <stdio.h>#include <stdlib.h>
void fun()
{
char *ptr = (char *) malloc(128);
printf("Vel Enter the details: ");
scanf("%s", ptr);
printf("Vel Entered value is = (%s) \n\n", ptr);
free(ptr);
return;
}
int main()
{
fun();
while(1) {
/* Added this while to make sure that the process is still running but we forget to
free the memory once come out from the fun() and dont have variable to track that memroy. */
sleep(1);
}
return 0;
}
No comments:
Post a Comment