edited by
507 views
2 votes
2 votes
#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;
    return a;
}



When it will give memory leak problem .. what should be changes ? pls explain in detail

edited by

1 Answer

Best answer
2 votes
2 votes
#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; 
}
selected by

Related questions

2 votes
2 votes
1 answer
1
sid1221 asked Nov 2, 2017
1,107 views
#include <stdio.h int main(){ float a=5.375; char *p; int i; p = (char*)&a; for(i=0; i<2; i++) printf("%x", (unsigned char)(p[i]^p[3-i])); retur...
2 votes
2 votes
1 answer
2
92komal asked Dec 20, 2017
1,131 views
Booth's coding in 8-bits for the decimal number -57 is: A 0-100+1000 B 0-100+100-1 C 0-1+100-10+1 D 00-10+100-1 plz explain this question
0 votes
0 votes
0 answers
4
mohitbawankar asked Dec 20, 2017
685 views
Assume that letters p, q, r, s, t and q have probabilities 1/2, 1/4, 1/8, 1/16, 1/32 and 1/32 respectively. The difference in the average length of the message without an...