I came across this over the net while I was studying some memory leak related stuff.
int* Function()
{
int arrays[10];
/* Some code here */
return &(arrays[0]);
}
The author says that the above piece of code is valid, but the memory that is returned will be reused by the next function you call, so the same memory will be used for two purposes. This is called a "hanging reference" and can cause horribly intermittent faults, or an old-fashioned "general protection fault".
It would be great if somebody can explain what is "hanging reference" & "general protection fault"
This doesn't exactly leak memory, since the allocated array will be automatically deallocated when the function returns. This is what is meant by a hanging reference, you are returning a pointer to some memory that was allocated on the stack. When the function returns, the stack allocated array is deallocated, so that location in memory could be overwritten by data for the next function call, so dereferencing the returned pointer will give an undefined value. This could well cause a general protection fault, as the value of the pointer could change such that it points outside of valid address space, dereffing such a pointer would cause a general protection fault.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With