0

There are many ways to return local variables from a function in C++, but why do some work and others don't? Like, I have provided two cases:

Case 1:

int* fun1()
{
    int x = 20;
    int* ptr = &x;
    return ptr;
}

int main()
{
    int* arr = fun1();
    cout << *arr;
    return 0;
}

Case 2:

int* fun2()
{
    int arr[100];
 
    arr[0] = 10;
    arr[1] = 20;
 
    return arr;
}
 
int main()
{
    int* ptr = fun2();
    cout << ptr[0] << " " << ptr[1];
    return 0;
}

Here both ptr variable from fun1() {case-1} and arr[] from fun2() {case-2} are local variables to their respective functions. So, why in case-1 does main() print the returned value from fun1() fine, but in case-2 when printing the return value it gives a segmentation fault?

Moreover, what can be a better alternative in both cases?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
amateur17
  • 9
  • 3
  • 5
    Both cases are UBs. – Jarod42 Jun 28 '21 at 15:44
  • they are both undefined. Undefined behavior can appear to work. I answered similar question recently: https://stackoverflow.com/questions/68098309/scope-and-lifetime-of-a-pointer-to-struct-which-is-local-to-a-function/68098538#68098538 The bottom line is: Undefined beahvior is undefined, no matter if it may appear to "work" – 463035818_is_not_an_ai Jun 28 '21 at 15:45
  • *"Moreover what can be better alternative in both cases"* return by value, int and `std::pair`/`std::array`. – Jarod42 Jun 28 '21 at 15:45
  • returning a reference or pointer to a function local variable is always wrong. – 463035818_is_not_an_ai Jun 28 '21 at 15:46

0 Answers0