+ 2
Can anyone explain working of this code in brief and fix the code?
4 ответов
+ 12
Just include the header file stdlib.h to remove the implicit declaration warning
+ 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.
+ 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
+ 2
For working of malloc, we have to include malloc.h file in c. You should include malloc.h file