Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dangling reference. Alternatives for dangling pointers and references?

The following code produces dangling references:

int main()
{
  int *myArray = new int[2]{ 100, 200 };
  int &ref = myArray[0];
  delete[] myArray;
  cout << ref;  // Use of dangling reference.
}

I know I shouldn't delete the array but in a large program what if somebody deletes memory to which I have a reference? Can it be somehow assured that no one deletes the array?

What is the best strategy against dangling references and dangling pointers?

like image 858
Chenna V Avatar asked Nov 24 '10 19:11

Chenna V


1 Answers

Don't delete the memory before you have finished with it.

Sounds stupid, but that's your only protection - properly understand who owns the memory behind each variable, and when it can safely be freed.

Smart pointers can help, but the above still applies.

It's possible some static analysis tools could identify the trivial case you have here, but even then that should be a second line of defence, with your first being discipline in memory management.

like image 181
Steve Townsend Avatar answered Sep 30 '22 17:09

Steve Townsend