+ 1
pointer still points to the value even after "free" function (void free(void *ptr)) is called
#include <stdlib.h> #include <stdio.h> int main(){ int *ptr; //a block of 10 ints ptr = malloc(10*(sizeof(*ptr))); if(ptr!=NULL) *(ptr+2)=50; //Assign 50 to the third int printf("%d\n",*(ptr+2)); free(ptr); printf("%d\n",*(ptr+2)); return 0; } In the above code, the printf statement still prints the value 50 even after deallocating the memory using "free" function.
3 Respostas
+ 2
Some nonstandard compiler produce undefined behaviour for some function.. All depends on their implementation details.
About free : It will just free the size of memory allocated by the previous memory allocation methods.
So may be in nonstandard compliers compliers may just clear value which is returned by previous memory allocation method. So values may be there until they are replaced by other values.. But I'm not sure. Just a guess... It's all depends on developers strategy..
Check this almost same example in same way.. It is freeing.. https://www.tutorialspoint.com/c_standard_library/c_function_free.htm
I guess that is may be because of not synchronisation case which is expressed in following free function undefined behaviour..
Read this for the free function undefined behaviour in some cases..
https://devdocs.io/c/memory/free
Hope it helps you..
+ 1
No. Iam getting garbage value.. Check again..
0
In the online compiler from sololearn, i am getting garbage value but when one tries here, https://www.tutorialspoint.com/compile_c_online.php one will not get the garbage value. I don't know why!! What is the difference between sololearn compiler and other c compiler?