-3

Why the dangling pointer in the following program shows the same memory address even after freeing the memory?

#include <stdio.h>
#include <stdlib.h>

int main()
{
int a = 1;

int *ptr_a = (int*)malloc((sizeof(int)));

ptr_a = &a;

printf("The address of 'a' is %p\n", ptr_a);

free(ptr_a); // A dangling pointer

printf("The address of 'a' is %p", ptr_a);

return 0;
}

I tried everything but still getting the same problem.

Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111
Debojit
  • 9
  • 1
  • 1
    Pointers hold an address. That address doesn't change just because what's there is no longer available. Why do you expect this to be different? – Etienne de Martel Aug 12 '23 at 04:49
  • 4
    1) Freeing memory does not change the value of the pointer that points to it, and 2) you are not freeing the memory you allocated but instead you are trying to free the address of a stack variable, which is bad news. – jkb Aug 12 '23 at 04:50
  • Oh, right, there's undefined behaviour in there too. – Etienne de Martel Aug 12 '23 at 04:53
  • 1
    Welcome to Stack Overflow! [don't cast malloc](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Barmar Aug 12 '23 at 04:55
  • 2
    Think about this: In C arguments are passed by value to a function. `free` is a function. How would it even be possible for `free` to change the address that is stored in a variable that is not visible to the function at all? Already from the fact that you call it `free(ptr)` and not `free(&ptr);` tells you that the value of `ptr` cannot be changed by the function. – Gerhardh Aug 12 '23 at 10:12

1 Answers1

1

The code first allocates memory by calling malloc, and stores the returned address in ptr_a. It then assigns the address of the local variable a to ptr_a. At this point, the address of the memory returned by malloc is lost, resulting in a permanent memory leak.

It then passes ptr_a, i.e. the address of a, to free. This is undefined behavior. You may only pass pointers obtained by malloc, realloc, calloc, etc. to free.

The pointer stored in ptr_a isn't changed by the call to free, so it prints the same address (unless something goes horribly wrong due to the undefined behavior caused by the bad call to free).

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41