0

I have the following program:

#include <iostream>
#include <string>

using namespace std;
using int_arr = int[3];

int& f(int_arr& arr, int index)
{
    return arr[index];
}

int main() {
    int arr[3] = {1, 2, 3};
    int& g = f(arr, 0);
    g = 5;

    std::cout << arr[0] << std::endl;
}

Is arr[index] returned by f considered a dangling reference?

I don't think this is a dangling reference since the arr object continues to exist even after f returns (so the reference is valid), but I wanted to confirm my understanding. I compiled this with -fsanitize=undefined and it compiled fine and produced the expected output.

ktqq99
  • 25
  • 5
  • 3
    No `g` references a member of the array `arr` (in the scope of `main`) which has the same lifetime. ( It would probably be better, for the sake of the question, if you called the local and the parameter by a different name. ) – Richard Critten Jan 13 '23 at 17:15

1 Answers1

1

No, arr and g have the same life time, so there's no dangling reference.

Note however that you can easily create a dangling reference with your function:

int empty;
int& ref = empty;

int &f(int arr[], int idx) { return arr[idx]; }
void g()
{
    int arr[] = { 1, 2, 3 };
    ref = f(arr, 0);
}

int main()
{
    g();
    // ref is accesable here and complete garbage
}
Blindy
  • 65,249
  • 10
  • 91
  • 131
  • 4
    I don't think your example correctly shows a dangling reference. You can't rebind a reference so the assignment inside `g()` just changes the value of the `int` "empty". – Blastfurnace Jan 13 '23 at 17:36