2

First I have a function to initialize an array and return a pointer pointed to its first element.

int* getPtrToArray()
{
    int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    return array;
}

And this function just creates an array not going to be used.

void testing()
{
    int junk[3] = {1234, 5678, 9101112};
}

Here is my main function:

int main()
{
    // #1
    int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int* ptr0 = array;

    cout << *ptr0 << endl;
    cout << ptr0[0] << endl;

    // #2
    int* ptr1 = getPtrToArray();

    cout << *ptr1 << endl;
    cout << ptr1[0] << endl;

    // #3
    testing();

    cout << *ptr1 << endl;
    cout << ptr1[0] << endl
}

The output results are:

1
1
1
2066418736  // "ptr1[0]" should be the same as "*ptr1", right?
2066418736  // since testing() does not modify the array, why "*ptr1" is changed?
2066418736

I think all these six outputs should be 1 (the first element in the array). Could anyone explains this to me? Thanks!

Yingbo Wang
  • 33
  • 1
  • 6
  • 1
    in getPtrToArray, can't return array, as it's a local variable, and it's address is not valid once function returns – DBug Nov 21 '15 at 01:40
  • You should get a warning like "address of stack memory associated with local variable 'array' returned" when you compile. – Eric Angle Nov 21 '15 at 01:56

3 Answers3

1

Please do not return the pointer to a local variable, or array. The memory of local variable will be reclaimed after the program runs out of the scope and thus caused undefined behavior.

Dong Li
  • 133
  • 6
1

array is local. When the function call returns, the memory is released. ptr1 is referencing undefined area.

int* getPtrToArray()
{
    int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    return array;
}
Nandu
  • 808
  • 7
  • 10
1

I seem to remember something like this working but it is an abusive C thing rather than a C++ thing.

If I remember correctly the stack does not bother wiping the old data and just says that it is free and then the data may or may not get corrupted the next time you initialize new data depending on how much you initialized before exiting scope and after exiting scope, the way it compiled, and function usage. The stack pointer just moves back to reclaim the memory and does not bother erasing the memory because that takes extra work.

You can get odd optimizations out of this but if you are programming in C++ you should not be using C arrays and instead should be using vectors or other C++ containers. On the other hand, if you are programming in C or an Assembly language, this kind of behavior is something that may be exploited.

Gamenotcore
  • 161
  • 4