0

I'm trying to understand how to use functions in C++ to return arrays. I want to understand what's going on here. This is my code, that I compile with g++ -Wall return_array.cpp -o return_array

#include <iostream>

int * do_something(int number){
    int viz[3] = {1,2,3};
    viz[2] += number;
    return &viz[0];
}


int main(){
    int *viz;
    viz = do_something(3);

    std::cout << viz[2] << "\n";
    return 0;
}

which gave me the following error:

return_array.cpp: In function ‘int* do_something(int)’:
return_array.cpp:4:6: warning: address of local variable ‘viz’ returned [-Wreturn-local-addr]
  int viz[3] = {1,2,3};

By my research, the error is due to the fact that I'm trying to access a pointer that has been deleted from the Stack once I leave the function's scope. However, if I run the code with a workaround:

int * do_something(int number){
        int viz[3] = {1,2,3};
        int *pointer;
        viz[2] += number;
        pointer = &viz[0];
        return pointer;
    }

it compiles and runs just fine. Isn't this new pointer in the precise same situation? Once I leave the function, it is out of scope and should be deleted from the Stack, by the same argument as before. What am I missing?

EDIT: My question here is not whether or not returning the pointer to a local array produces an error. It should and it does. The question is why the pointer that has been assigned to the pointer to the same array does not!

Sermal
  • 187
  • 1
  • 9
  • There is only so much the compiler can do for you. If you insist on working around a valid error instead of trying to address the actual error condition, the compiler may or may not flag it as an error. It is indeed the same situation but since you are using an alias the compiler isn't able to check for this issue where as with the return of the address of the array it could. Compilers are not omniscient. – Richard Chambers Sep 28 '17 at 01:12
  • Thank you, I believe this clarifies my doubt. I was not aware that this kind of error would not be detected by the compiler. I shall take this into account in the future. – Sermal Sep 28 '17 at 01:28

1 Answers1

0

Once control leaves the function, the array is out of scope. It might be erased, it might not. That region of memory might still contain those numbers for a while, and it might not. Trying to read it might work, or it might do anything. This is known as undefined behavior, and it is a difficult thing to detect and a good thing to avoid.

Beta
  • 96,650
  • 16
  • 149
  • 150
  • Ah, I think I understand now, thanks to Richard Chambers's comment and your response. So it is in fact the same situation, but in one case, the compiler complains about it and in the other it does not. So I cannot expect to obtain reliable results with this procedure. – Sermal Sep 28 '17 at 01:17