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;
}
CodePudding user response:
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.
CodePudding user response:
A pointer is simply an index into a memory. It's not the 'data' itself that it's pointing at. It's the index of the memory it's pointing at.
I'm going to make an assumption here and say that
newclass = NULL;
is done by mistake because if not you now have a memory leak.
There is nothing wrong with having multiple pointers pointing into the same memory if you manage all those pointers properly (talking purely about technicality and not making any statements regarding on whether this is a bad practice or not.). Problem is that, if you deallocate that memory and forget to manage even a single one of those pointers and try to do an operation on that deallocated memory block via that pointer, than that's definitely a problem.
The fact that the memory block a pointer is pointing to gets deallocated doesn't deallocate the 'pointer' itself. You can still use your pointers for various stuff; from pointer arithmetic to making them point to a different block of memory. Golden rule is not doing any memory operations on the memory address your pointer was previously indexing.
