1

I have the following code.

int *x = somefuction();//return array of two elements
string s;
cout << x[0] << " and " << x[1];

This code prints unexpected values. But if I comment out "string s;" row it works fine. What is the reason?

Some function is:

int* getRowCol(int l){
int min = floor(sqrt(l));
int max = ceil(sqrt(l));
int area = 100000;
int result[2];
for (int col = min; col <= max; col += 1){
    for (int row = min; row <= col; row += 1){
        if (col*row < area && row*col>=l){ 
            area = row*col;
            result[0] = row;
            result[1] = col;
        }
    }
}

return result;
}
chamathabeysinghe
  • 858
  • 2
  • 13
  • 34

1 Answers1

3

You are returning a pointer to some value that exists on the stack in someFunction(). I.e. a local variable. These don't live past the end of the function call.

int* someFunction()
{
    int someInts[2] = {10, 20}; // only exists inside someFunction
    return someInts;
}

Perhaps you should use a std::vector, which will take care of allocating memory in a way that is safe to use like this. It is Undefined Behaviour to dereference this returned pointer in any way. Your code could do absolutely anything. Try something like this instead:

std::vector<int> someFunction()
{
    std::vector<int> someInts {10, 20};
    someInts.push_back(30);
    return someInts;
}
BoBTFish
  • 19,167
  • 3
  • 49
  • 76