When I try to use realloc to allocate memory for a pointer which has been free‘d, I get a segmentation fault. Although I don’t face this issue if I use malloc instead.
As per my understanding after the variable has been free‘d it is equivalent to a NULL pointer, then why is this unexpected behavior? Am I missing something?
A
NULLpointer is a pointer whose value isNULL; standard functions likereallocknow how to interpret this value.A pointer to some memory that has been freed is now an invalid pointer; its value doesn’t change.
reallocdoesn’t know that it’s invalid, and will try and access it, leading to the seg-fault.