#include <stdio.h>
#include <stdlib.h>
int* fun();
int main()
{
int *a = fun();
printf("%d",*a);
return 0;
}
int* fun()
{
int *a =(int*) malloc(sizeof(int));
*a = 10;
a=NULL;
//free(a);
return a;
}
If there is a memory leak problem, a=NULL will be added , but free(a) not added as shown above. That means u have created a memory and then put value inside it. After that u making pointer NULL the memory location, Means no more that pointer is available, but stiil memory is not freed. But after that u want to return that value of a, which is not free as of now. So, this problem is called memory leak .
To overcome this problem, we need to free or delete that memory location.
________________________________________________________________________
Just opposite scenario happens when there is memory leak. Here memory got freed, but forgot to make pointer NULL. SO,though memory is freed, pointer still pointing to some memory location. So, before freeing, if u want to print value 5, it will give compiler error. That is dangling pointer issue.
#include <stdio.h>
#include <stdlib.h>
int* fun();
int main()
{
int *a = fun();
printf("%d",*a);
return 0;
}
int* fun()
{
int *a =(int*) malloc(sizeof(int));
*a = 10;
free(a);
//*a=5;
//ptr=NULL;
return a;
}