memcmp strangely fails returning array

300 views Asked by At

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?

1

There are 1 answers

0
ApproachingDarknessFish On

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