1

i would like to ask, why this code doesnt work...

int* funkce(){
    int array[] = {1,2,3,4,5};
    return(array);
  }

int main(){

    int* pp = funkce();
    int* ppk = pp+5;

    for (int *i = pp; i!=ppk; i++){
        cout << (*i) << endl;
    }

    system("PAUSE");
    return(0);
}

This code display:

1
16989655
4651388
- // -
253936048

So the poniter is out of array... But how is possible, that this code with array in Main is ok?

int main(){

    int a[] = {1,2,3,4,5};
    int* pp = a;
    int* ppk = pp+5;

    for (int *i = pp; i!=ppk; i++){
        cout << (*i) << endl;
    }
    system("PAUSE");
    return(0);
}

this code displayed:

1
2
3
4
5

Could you explain to me, why the first one doesnt work? Thank you!

Frenky
  • 35
  • 8
  • http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope – chris Oct 24 '14 at 00:04

2 Answers2

6

You're returning a pointer to a temporary which goes out of scope when the function ends. If you want to have a function return an array, you need to do one of:

std::array<int, 5> func() {
    // stack-allocated
    std::array<int, 5> a = {1, 2, 3, 4, 5};
    return a;
}

std::vector<int> func() {
    // heap-allocated
    std::vector<int> a = {1, 2, 3, 4, 5};
    return a;
}

int* func() {
    // heap-allocated, you have to remember to delete it
    int* a = new int[5]{1, 2, 3, 4, 5};
    return a;
}

etc. There's more options, but this should give you a good start.

Barry
  • 286,269
  • 29
  • 621
  • 977
  • std::vector is the one to use (IMHO) – pm100 Oct 23 '14 at 23:54
  • @pm100 Why not std::array? – Neil Kirk Oct 24 '14 at 00:43
  • because the std:array will return a copy of the array (more expensive in general although probably trivial here). std::vector returns a pointer to the array on the heap. And the perf of vector and array are the same – pm100 Oct 24 '14 at 15:55
  • @pm100 If you have `std::array a = func()`, the array won't be copied, it will be constructed in place. The determination to use one or the other is entirely use-case based. – Barry Oct 24 '14 at 16:06
  • according to your own comment it was allocated on the stack of the func. Cant be on the func stack when I return it – pm100 Oct 25 '14 at 20:54
  • @pm100 Look up return value optimization. – Barry Oct 25 '14 at 22:53
  • in this case its optimized I agree, but in general passing around std:arrays results in them being copied, std::vector doesnt result in copy of elements – pm100 Oct 26 '14 at 18:29
  • @pm100 It does if you copy the vector. – Barry Oct 26 '14 at 18:34
0

Never return a local a pointer/reference to a variable, that memory is freed/re-used on return.

Using that dangling reference is Undefined Behavior and has unpredictable consequences.

Return an object, a pointer to heap-allocated memory, or save into a caller-supplied buffer.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118