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?
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.
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