Why do you think that calling the free function to deallocate memory previously allocated using malloc or other C library functions for dynamic memory allocation would change the value of any pointer variables used to hold the address of the dynamic allocation? Have you read the documentation for the free function? If you have read it then does it say anything about changing the value of pointers used to hold the addresses of dynamically allocated memory? Stated simply, the content of those pointer variables is the responsibility of the programmer. "Use after free" is a classic programming error.
Why the free function is not working here?

Debojit Acharjee
455
Reputation points
I used malloc function in the following program to allocate memory to a pointer and freed it using free function but why the memory address is same after freeing it?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr_a = malloc(sizeof(int));
printf("The address of \"ptr_a\" is %p\n", ptr_a);
free(ptr_a);
printf("The address of \"ptr_a\" is %p\n", ptr_a);
return 0;
}
Output:
The address of "ptr_a" is 00871598
The address of "ptr_a" is 00871598
Developer technologies | C++
3,977 questions
3 answers
Sort by: Most helpful
-
-
Debojit Acharjee 455 Reputation points
2023-08-16T13:42:47.24+00:00 It's obvious that after freeing a pointer using the free function the memory address would remain the same but you are wrong in one way that the value of that memory address changes after freeing it.
#include <stdio.h> #include <stdlib.h> int main() { int a = 1; int *ptr_a = malloc(sizeof(int)); *ptr_a = a; printf("The address of \"ptr_a\" is %p\n", ptr_a); printf("The value of \"ptr_a\" is %d\n", *ptr_a); free(ptr_a); // Becomes a dangling pointer printf("The address of \"ptr_a\" is %p\n", ptr_a); printf("The value of \"ptr_a\" is %d\n", *ptr_a); // Will show garbage value of dangling pointer return 0; }
The above program proves it.
-
Bruce (SqlWork.com) 78,006 Reputation points Volunteer Moderator
2023-08-16T23:13:05.2966667+00:00 also
free(ptr_a);
is passed the value of ptr_a, and can not update the variable itself.