Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are we able to access the pointer after deallocating the memory?

As per my understanding,

free() is used to deallocate the memory that we allocated using malloc before.

In my following snippet, I have freed the memory i have allocated. But i was able to access the pointer even after freeing? How it is possible?

How free works internally?

#include<iostream>
using namespace std;

int main()
{
   int *p=(int *)malloc(sizeof(int));
   *p=17;
   free(p);
   *p=*p+1;
   printf("\n After freeing memory :: %d ",*p );
   return 0;
}
like image 815
VINOTH ENERGETIC Avatar asked Dec 01 '25 20:12

VINOTH ENERGETIC


2 Answers

You can certainly continue to use p after calling free(p) and nothing will stop you. However the results will be completely undefined and unpredictable. It works by luck only. This is a common programming error called "use after free" which works in many programs for literally years without "problems" -- until it causes a problem.

There are tools which are quite good at finding such errors, such as Valgrind.

like image 196
jeremycole Avatar answered Dec 03 '25 12:12

jeremycole


Accessing a dangling pointer will result in undefined behavior. A dangling pointer is the one which is already freed.

like image 37
Vijay Avatar answered Dec 03 '25 12:12

Vijay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!