Search code examples
c++arrayspointersparameters

C++ returned array loses it's values depending on if any new array is declared or not. Its losing it if yes


I wrote a simple c++ program where i am getting a simple float Array from a function. Then I call a function where the generated Array is a parameter of. I print the first value of the Array through the function. It works! BUT when i am declaring another array in the function before i print the value from the first array, the printed value is not the expected one. MAGIC!

CODE THAT DOESN'T WORK:

#include <iostream>;

float* getArray() {
    float Array[] = { 4 };
    return Array;
}

void compute(float* Array) {

    bool newArray[1];
    float content = Array[0]; //breakpoint: content will be -107374176.
    std::cout << content;

}

int main() {

    float* Array = getArray();
    compute(Array);
}

OUTPUT: -1.07374e+08

When removing the line "bool newArray[1];" (line 10) the code starts to work.

OUTPUT: 4

Test it your self! Can someone explain me why this happens?


Solution

  • Your main function has a bug. It passes a pointer to Array to compute, which dereferences it. But Array is out of scope at this point since its scope ends when getArray ends. So you are trying to access an object that no longer exists. That is undefined behavior and produces completely unpredictable results.

    Arguably, getArray also has a bug since it always returns a pointer to an object that no longer exists. So there is no way to use it. Whether or not that's a bug depends on what the caller is supposed to be able to do with the returned value which cannot be determined due to the lack of comments.