WHY THE DANGLING POINTER SHOWS THE VALUE AND ADDRESS EVEN AFTER FREEING IT USING FREE FUNCTION?

Debojit Acharjee 455 Reputation points
2023-07-27T17:13:32.6566667+00:00

In the following program a pointer has been freed using the free() function but still it prints the address and value of the initialized variable.

#include <stdio.h>

#include <stdlib.h>

int main()

{

  int a = 1;

  int *a_ptr = &a;

  printf("The value of 'a' is %d\n", *a_ptr);

  free(a_ptr);

  printf("The value of 'a' is %d", *a_ptr);

  return 0;

}

Ourput:

User's image

Developer technologies | C++
{count} votes

2 answers

Sort by: Most helpful
  1. P a u l 10,761 Reputation points
    2023-07-27T17:21:01.77+00:00

    Just referencing this article:

    https://www.tutorialspoint.com/c_standard_library/c_function_free.htm

    "The C library function void free(void *ptr) deallocates the memory previously allocated by a call to calloc, malloc, or realloc."

    So because a is a stack allocated variable rather than a block of memory allocated by one of the *alloc functions the free function may not affect it at all (i.e. it's undefined behaviour).

    1 person found this answer helpful.

  2. Barry Schwarz 3,746 Reputation points
    2023-07-27T19:06:17.7666667+00:00

    Nowhere in your code do you print any addresses.

    The first printf statement does not print the address of a despite its claim to do so. It prints the contents of a which happens to be 1. If you really want to print the address of a, you would remove the dereference operator from the argument and adjust the format specification.

    Your free statement causes undefined behavior because you are attempting to free memory that what was not allocated by malloc. When your code is run on a Windows system using Visual Studio, it fails on the free statement. So why don't you tell us how you got it to execute the second printf statement.

    1 person found this answer helpful.

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.