Memory leak In simple words
: you create memory dynamically and Forget to detele that memory.
So solution Make that Free(variable) (which contain the address of that variable)
Dangling Problem:
You Freed the dynamically allocated memory, But still point to that memory.
So solution Make that variable= null (which contain the address of that variable).
#include<stdio.h>
int *assignval (int *x, int val) {
*x = val;
return x;
}
void main () {
int *x = malloc(sizeof(int)); memory allocated dynamically to *x which point int data.
if (NULL == x) return; this case to chcek memory availiable or not if not then x= null is happen
x = assignval (x,0); this will make function call and assign *x= 0 and return addrees of same memory
if (x) { since x= memory address
this condition is true
x = (int *)malloc(sizeof(int)); New memory assign to x
if (NULL == x) return; this is true if memory availiable
x = assignval (x,10); This assign memory location *x= 10.
}
printf("%d\n", *x); print *x= 10
free(x); we freed last allocated memory but not the memory which is assigned 1st time.
}
Dangling problem is arise if we use printf("%d\n", *x); after free(x);