Will A Pointer P1 Be Accessible After Freeing Another Pointer P2 Containing The Same Address As P1?
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;
}
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.
Related Questions
- → OctoberCMS Backend Loging Hash Error
- → "failed to open stream" error when executing "migrate:make"
- → OctoberCMS - How to make collapsible list default to active only on non-mobile
- → Create plugin that makes objects from model in back-end
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → How to install console for plugin development in October CMS
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → How to update data attribute on Ajax complete
- → October CMS - Conditionally Load a Different Page