Why the free function is not working here?

Debojit Acharjee 455 Reputation points
2023-08-16T10:22:11.64+00:00

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++
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. RLWA32 49,636 Reputation points
    2023-08-16T13:22:01.6933333+00:00

    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.

    0 comments No comments

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


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

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.