Ad

Will A Pointer P1 Be Accessible After Freeing Another Pointer P2 Containing The Same Address As P1?

- 1 answer

Is there some sort of risk that the program might go to segmentation fault if you assign a pointer the same address to another pointer with another type definition of the same struct, then you free the previous one and just use the last assigned with the same address?

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

struct Class{
 int data;
 struct Class *next;
}key;

int main(){
 key *newclass = malloc(sizeof(*newclass));
 newclass->data = 5;
 newclass->next = NULL;
 
 key *newclass2;
 newclass2 = newclass;
 
 newclass = NULL;
 free(newclass);

 printf("%d", newclass2->data);
 
 return 0;
}
Ad

Answer

For starters it seems there are typos in the structure definition. I think you mean

typedef struct Class{
 int data;
 struct Class *next;
}key;

After this assignment

 newclass2 = newclass;

the both pointers point to the same dynamically allocated memory.

Then the pointer newclass was reassigned with NULL

 newclass = NULL;

So calling the function free for a null pointer

 free(newclass); 

has no effect.

The pointer newclass2 still points to the dynamically allocated memory that you should free then it is not required anymore.

 free(newclass2);

If you will remove this assignment

 newclass = NULL;

then after calling free with this pointer

 free(newclass); 

the value stored in the pointer newclass2 will be invalid and you may not use it to access the already freed memory.

But the both pointers as local variables are still alive and you may assign to them new values.

Ad
source: stackoverflow.com
Ad