C++ [Warning] address of local variable 'bestIdx' returned [-Wreturn-local-addr]

349 Views Asked by At

I'm currently writing a function that returns an array but it keeps showing [Warning] address of local variable 'bestIdx' returned [-Wreturn-local-addr] while compiling. What does this mean?

Below is the function I wrote:

int *findMostPrefered(int toyCnt, int childrenCnt, int prefer[][20], bool toyNum[], bool childrenNum[]){
int max = prefer[0][0], bestIdx[2]={0};
for(int i=(childrenCnt-1); i>=0; i=i-1){
    if(childrenNum[i] == 0){
        for(int j=(toyCnt-1); j>=0; j=j-1){
            if(toyNum[j] == 0){
                if(prefer[i][j] >= max){
                    max = prefer[i][j];
                    bestIdx[0] = i;
                    bestIdx[1] = j;
                }
            }   
        }
    }
}
return bestIdx;
}
1

There are 1 best solutions below

6
Vlad from Moscow On

You declared the block scope array bestIdx with automatic storage duration

int max = prefer[0][0], bestIdx[2]={0};

that will not be alive after exiting the function. So the returned pointer to the first element of the array will be invalid. Dereferencing such a pointer invokes undefined behavior.

Instead of the array with two elements you could use an object of the type std::pair<int, int> and return it. For example

#include <utility>

//...

std::pair<int, int> findMostPrefered(int toyCnt, int childrenCnt, int prefer[][20], bool toyNum[], bool childrenNum[]){
int max = prefer[0][0];
std::pair<int, int> bestIdx( 0, 0 );
for(int i=(childrenCnt-1); i>=0; i=i-1){
    if(childrenNum[i] == 0){
        for(int j=(toyCnt-1); j>=0; j=j-1){
            if(toyNum[j] == 0){
                if(prefer[i][j] >= max){
                    max = prefer[i][j];
                    bestIdx.first = i;
                    bestIdx.second = j;
                }
            }   
        }
    }
}
return bestIdx;
}