1
#include <iostream>
using namespace std;

int* createArray();

int main() {
    int *arr = createArray();
    cout << "Main: " << arr << endl;

    arr[0] = 0;
    arr[1] = 1;

    cout << arr[0] << endl;
    cout << arr[1] << endl;
}

int* createArray() {
    int arr[2];
    cout << "createArray()1: " << arr << endl;
    return arr;
}

I don't understand why if I only call this statement

cout << arr[0] << endl;

or

cout << arr[1] << endl;

can show a correct value. But if I call both statement, it will show

createArray()1: 00AFFAF4
Main: 00AFFAF4
0
11533068  //Don't show 1
SinLok
  • 589
  • 1
  • 5
  • 19
  • [Compile with warnings.](http://coliru.stacked-crooked.com/a/2084c17e9d9ca5fd) – chris Jan 26 '17 at 09:01
  • [Can a local variable's memory be accessed outside its scope?](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794#6445794) – songyuanyao Jan 26 '17 at 09:01
  • You can not return a pointer to an object allocated on the stack, since it will be destroyed as soon as you exit. Use [malloc](http://www.cplusplus.com/reference/cstdlib/malloc/). – xzoert Jan 26 '17 at 09:03
  • @xzoert no. Don't use malloc in C++. – eerorika Jan 26 '17 at 09:15
  • ops, it's c+++, right. sorry! – xzoert Jan 26 '17 at 09:21

2 Answers2

5

The pointer returned by createArray points to a non-existing object. The local array was destroyed when the function returned. When you dereference the dangling pointer in main, the behaviour of your program is undefined.

Solution: Don't ever return pointers or references to local variables. In this case, you could for example return a copy of the array. You cannot return a raw array by value, but you can return a wrapper structure like std::array<int, 2>.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • I don't understand why only call cout << arr[0] << endl; OR cout << arr[1] << endl; is still working – SinLok Jan 26 '17 at 09:08
  • @SinLok What do you mean by "still working"? The behaviour is undefined. – eerorika Jan 26 '17 at 09:09
  • If I only call cout << arr[0] << endl; it will show 0. If I only call cout << arr[1] << endl; it will show 1. But if I call both statement, it will display 0 and 11533068 in visual studio – SinLok Jan 26 '17 at 09:12
  • @SinLok in both cases the behaviour is undefined. – eerorika Jan 26 '17 at 09:13
0

You are returning a pointer to local variable which is destroyed at function block end.

But beware, when you use new operator, you need to use delete somewhere else (atleast without of use of smart pointers).

Solution:

int* createArray() {
    int* arr = new int[2];
    // your code
    return arr;
}