Difference between dangling pointer and memory leak ( C Interview Question -4)
What is memory leak in C?
Memory leak occurs when you allocated memory using malloc or calloc, but forget to free the allocated memory i.e., forget to call free()
This will cause a serious issue in programs like daemons or servers which will be running for a long amount of time.
Example:
#include<stdio.h>
void function()
{
int *ptr = (int *)malloc(1000);
/* Perform Some work*/
/* Returned without calling free*/
}
int main()
{
while(1)
{
func();
}
return 0;
}
In order to avoid memory rule, you have to free the allocated memory after you complete your work of using it.
In order to find out if there is any memory leak occurring in the program, you can use tools like valgrind.
What is a dangling pointer?
Dangling pointers are the pointers which are pointing to the memory location which is already freed. If you try to access that particular memory location, it may lead to segmentation fault.
Example:
#include <stdio.h>
int main()
{
char *ch = (char *)malloc(10);
ch ="Hello";
free(ch);
ch[1] = 'a'; //dangling pointer
return 0;
}
In order to avoid this, you have to assign the pointer to NULL after freeing the memory.
Memory leak occurs when you allocated memory using malloc or calloc, but forget to free the allocated memory i.e., forget to call free()
This will cause a serious issue in programs like daemons or servers which will be running for a long amount of time.
Example:
#include<stdio.h>
void function()
{
int *ptr = (int *)malloc(1000);
/* Perform Some work*/
/* Returned without calling free*/
}
int main()
{
while(1)
{
func();
}
return 0;
}
In order to avoid memory rule, you have to free the allocated memory after you complete your work of using it.
In order to find out if there is any memory leak occurring in the program, you can use tools like valgrind.
What is a dangling pointer?
Dangling pointers are the pointers which are pointing to the memory location which is already freed. If you try to access that particular memory location, it may lead to segmentation fault.
Example:
#include <stdio.h>
int main()
{
char *ch = (char *)malloc(10);
ch ="Hello";
free(ch);
ch[1] = 'a'; //dangling pointer
return 0;
}
In order to avoid this, you have to assign the pointer to NULL after freeing the memory.
Comments
Post a Comment