11

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?

Kirill Kobelev
  • 10,252
  • 6
  • 30
  • 51
Chenna V
  • 10,185
  • 11
  • 77
  • 104
  • 1
    http://stackoverflow.com/questions/395123/raii-and-smart-pointers-in-c. Or in this example, the best alternative is to not do it. – Steve Jessop Nov 24 '10 at 19:55
  • 1
    The best alternative to a dynamically allocated array is `std::vector`. There is practically very little need in C++ to use `new[]` and `delete[]`. - But even then, iterators and references do get invalidated easily. Generally you just shouldn't have long-term references to things who might not have a long lifetime. – UncleBens Nov 24 '10 at 20:19
  • Thanks Bens. "shouldn't have long-term references to things who might not have a long lifetime." I'll follow that advice – Chenna V Nov 24 '10 at 20:20

5 Answers5

14

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.

Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
  • 1
    i know i shouldn't delete the memory, but this can't be controlled in a large program. I cannot ask all developers not to delete arrayXYZ. but I think smartpointers are what I was looking for. Thanks Steve – Chenna V Nov 24 '10 at 20:00
  • But again the problem is I cannot have a collection or array of smart pointers, can I ? – Chenna V Nov 24 '10 at 20:03
  • are you sure I can use smart pointers with arrays? I think I read about auto_ptr that it cannot be used with arrays, is that the same case with smart pointers? – Chenna V Nov 24 '10 at 20:05
  • 1
    @blueskin, smart pointers such as shared_ptr are safe for use in arrays. Its only auto_ptr which has odd semantics causing problems. – Winston Ewert Nov 24 '10 at 20:13
  • 2
    @blueskin: I'm quite sure that even with smart pointers, undisciplined programmers can still screw up (e.g by storing plain pointers to the held object). Even with smart pointers you'll have to follow best practices. - Getting things right would be simpler, though. – UncleBens Nov 24 '10 at 20:16
8

Keep them scoped properly:

int main(){
  int *myArray;
  myArray = new int[2]{ 100, 200 };
  {
    int& ref = myArray[0];
    // use the ref here
    cout<<ref;  \\no longer a dangling reference
  } // ref falls out of scope here
  delete[] myArray;
 }
John Dibling
  • 99,718
  • 31
  • 186
  • 324
5

Patient: Doctor, it hurts when I do this...

Doctor: Then stop doing it...

Do not release memory while having a reference to it.


EDIT

The only way to catch that is to debug, have good unit tests and run under valgrind, or run your program under valgrind.

BЈовић
  • 62,405
  • 41
  • 173
  • 273
  • I added more to the question. my question wasn't representing completely what I was trying to ask. Thanks – Chenna V Nov 24 '10 at 20:01
  • 1
    @blueskin the answer (and all others) are still valid. "Do not do that", and there are no ways to check whether your reference is invalid (or pointer points to an invalid memory location) – BЈовић Nov 24 '10 at 20:04
  • 1
    ya.. I understand. sadly thats true.. what if I am asked this in my interview and asked for a solution. I cannot say "Don't do that" :D.. – Chenna V Nov 24 '10 at 20:07
4

All of the answers here have been "be careful!", and "use good programming practices!".
That's not a very satisfying answer. These problems have existed in C for 40+ years, and they are still common in any C++ project of significant size.

The biggest guidelines you'll hear people recommend are:

  • Use smart pointers
  • Use RAII

Both are true, but there is more you can do.

In 2015, the Standard C++ Foundation released the Guidelines Support Library.

You can write C++ programs that are statically type safe and have no resource leaks. You can do that without loss of performance and without limiting C++’s expressive power. This model for type- and resource-safe C++ has been implemented using a combination of ISO standard C++ language facilities, static analysis, and a tiny support library (written in ISO standard C++).

I recommend you use GSL's Owner<> with a static analysis tool.
That will guarantee safe behaviour.

Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
3

Good programming practices. The compiler gives you more than enough rope to hang yourself with; it's your responsibility to make sure you don't.

In other words, if you don't take references to an array, and then delete it, then you won't have problems.

"But, what if it happens anyway?"

There's no simple answer, really. It's all about training, and knowing how to use the tools you're trying to use.

Mike Caron
  • 14,351
  • 4
  • 49
  • 77