I have come across a very confusing thing. I have made a local char array in a function, and return the array name, but the return value is null?
char* get_string(){
char local[] ="hello world\n";
cout<<"1"<<(int)local<<endl;//shows a reasonable value
return local;
}
int main(){
char* p = get_string();
cout<<"2"<<(int) p<<endl;//shows 0
return 0;
}
I know it is not good to use a local variable, because when the function returns, the stack part that the local variable occupies would be used by other function calls, but I think this should return the address of the first element of the array, should not be null. I'm very confused; any help would be appreciated.
I use QT 32 version, compiler is MSVC2015 (I am at baby stage about compiler; not even sure that MSVC is compiler name).
--updated, I think this question is not a duplicate of this Returning an array using C I know it is not valid to use atomic/local storage outside the scope, and my question is why the return value becomes 0 despite its inappropriate use.
--ok, thank you, everyone. I think I found the answer. I see the assembly code of the function char* get_string()
, the last part of the assembly code is this
0x44bce7 mov $0x0,%eax
0x44bcec leave
0x44bced ret
I think this is implementation defined, hard coded in the compiler, if I return the address of a local variable, then %eax
or %rax
is set to 0.