-2

I have C++ code that looks like this:

static int* ArrayGenerator()
{
    int temp[1] = {9};
    return temp;
}

static int* ArrayGenerator(int i)
{
    //parameter is just for demonstration
    int temp[1] = {9};
    return temp;
}

int _tmain(int argc, _TCHAR* argv[])
{
    int arr1[1] = {9};
    printf("arrays are %s equal\n\n", (memcmp(arr1, ArrayGenerator(), 1) == 0) ? "" : "not");
    printf("arrays are %s equal\n\n", (memcmp(arr1, ArrayGenerator(1), 1) == 0) ? "" : "not");
}

The first gives me 'are equal' the second gives me 'are not equal'.

Why is this?

happygilmore
  • 3,008
  • 4
  • 23
  • 37

1 Answers1

0

You cannot return local pointers from a function. When you return temp from the functions it passes out of scope and the memory is no longer valid. This causes undefined behavior. I already explained this here

Community
  • 1
  • 1
ApproachingDarknessFish
  • 14,133
  • 7
  • 40
  • 79