Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is "hanging reference" & "general protection fault"?

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"

like image 344
Keerthi Ranganath Avatar asked Apr 18 '13 10:04

Keerthi Ranganath


1 Answers

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.

like image 75
JS. Avatar answered Sep 28 '22 19:09

JS.