+ 2

Can anyone explain working of this code in brief and fix the code?

https://code.sololearn.com/cpkLW5r1tSz2/?ref=app

13th Jan 2020, 1:27 PM
Preity
Preity - avatar
4 Answers
+ 12
Just include the header file stdlib.h to remove the implicit declaration warning
13th Jan 2020, 2:02 PM
Nova
Nova - avatar
+ 6
#include <stdio.h> #include <stdlib.h> //add this int main() { char *a; a = malloc(10); // it returns a void pointer since it is not type casted to any specific type. The malloc has allocated a chunk of memory with 10 blocks. getFree(a); // function call if(a==NULL) // now you should observe that both a and ptr were pointing to the same memory address but only ptr is made Null and there is no change occurred on a. So this line fails. printf("null"); else printf("not null"); // this is executed return 0; } --------------------------------------------------------------- void getFree(void *ptr){ // a void pointer is now pointing to the same memory address as the 'a'. if(ptr!=NULL){ // this line is true because there is some address pointed by ptr. free(ptr); // memory deallocated ptr=NULL; // ptr is now not pointing to any address. } return; // back to next line of call } Edit: the above explanation could be wrong because concepts of C have faded with time. I just tried.
13th Jan 2020, 2:30 PM
Avinesh
Avinesh - avatar
+ 5
If you return the pointer ptr from the function and assign it to 'a' then you would get the answer as null. https://code.sololearn.com/c3ReE0s52M6c/?ref=app
13th Jan 2020, 2:51 PM
Avinesh
Avinesh - avatar
+ 2
For working of malloc, we have to include malloc.h file in c. You should include malloc.h file
13th Jan 2020, 1:58 PM
Akshay Harshora
Akshay Harshora - avatar