pointer still points to the value even after "free" function (void free(void *ptr)) is called | SoloLearn: Learn to code for FREE!


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.

5/3/2020 4:13:15 PM


4 Answers

New Answer


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..


Free does not clear the memory nor does it change what the pointer points to. That is up to the developer. Free releases the allocated memory to be used for future allocation. Once freed, and that memory is available for allocation, it may be overwritten by something else that allocates memory. There is no guarantee that the value there will remain intact. There is also no guarantee that the value will change. It's better to understand how it works and handle it accordingly within your code.


No. Iam getting garbage value.. Check again..


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?