Maker Pro
Maker Pro

Dangling pointers

Harald Kapp

Moderator
Moderator
Nov 17, 2011
13,700
Joined
Nov 17, 2011
Messages
13,700
After free(dp) the pointer dp is invalid. If you try to use it after free(), it points to a location that is no longer assigned and thus can create havoc in your system. The pointer is "dangling" as it is no longer attached to a defined location (defined in the sense of having a defined content).
Of course you can re-use the pointer after free(), but only after you assign a new valid value to it, e.g. by a new malloc() instruction.
What this means is that you use the memory location of the pointer to store a new value, but you do not use the old pointer value any longer.
 

champ1

Jul 17, 2018
55
Joined
Jul 17, 2018
Messages
55
Of course you can re-use the pointer after free(), but only after you assign a new valid value to it, e.g. by a new malloc() instruction.
.
I am getting output 20 even after freeing pointer dp without calling malloc
Code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
    int *dp = malloc(sizeof(*dp));
    *dp = 10;
    free(dp);         
    *dp = 20;
    printf(" %d", *dp);
}
 

Nanren888

Nov 8, 2015
622
Joined
Nov 8, 2015
Messages
622
The memory is not gone. It just no longer officially belongs to you, or to this main function. Nothing else has changed this memory, so the value is still there. Maybe try mallocing another variable with another pointer & see if it overlays the first one. Say set the new pointer to some other value and see ifd the original one changes value.
It is clear that one should not use memory that is no longer allocated to you, so I'm not sure what the question is.
 

Harald Kapp

Moderator
Moderator
Nov 17, 2011
13,700
Joined
Nov 17, 2011
Messages
13,700
I am getting output 20 even after freeing pointer dp without calling malloc
This may happen on the computer you are on. It may not happen the next time you try this. You may even get an error message if the memory location the pointer points at has been reclaimed by another process in the meantime.
Do never rely on pointers still pointing to valid date after the pointer has been freed()!
 
Top