-3

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?

Shooper
  • 3
  • 1
  • The compiler should be giving you a warning telling you not to return arrays from functions. Study the dup for more info. – Ken Y-N Sep 02 '22 at 04:14
  • I get this running error `Program returned: 139` different from what you said. – mariolu Sep 02 '22 at 04:25

1 Answers1

0

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.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278