struct test{
char c_arr[1];
};
test array[1] = {{1}};
test get(int index){
return array[index];
}
int main(){
char* a = get(0).c_arr;
return 0;
}
Compiling this with g++
has no warnings but with clang++
prints the following:
warning: temporary whose address is used as value of local variable 'a' will be destroyed at the end of the full-expression
Is this incorrect? does get(0).c_arr
not return a pointer to a global array?
or does get(0)
return a temporary variable and the compiler thinks c_arr
is just an instance of it, and not global, by mistake?
Why passing this temp variable to a function works without warnings?
void call(char* in){}
int main(){
call(get(0).c_arr);
return 0;
}
get
returns by-value, then get(0)
does return a temporary which gets destroyed after the full expression, left a
being a dangling pointer.
Note that the returned temporary test
is copied from array[index]
, including the array data member c_arr
. a
is supposed to point to the 1st element of the data member array c_arr
of the temporary test
, after the full expression (i.e. the ;
in char* a = get(0).c_arr;
) the whole temporary test
(and its data member c_arr
) is destroyed, then a
becomes dangling.
If get
returns by-reference then it'll be fine.
test& get(int index){
return array[index];
}
EDIT
The code you added is fine. The temporary is destroyed after the full expression, i.e. after ;
in call(get(0).c_arr);
. The pointer passed to call
remains valid inside call
.