Reputation: 151
I have a code like that:
#include <iostream>
using std::cout;
const int ARR_SIZE=5;
int arr[ARR_SIZE];
int (*five(int first))[ARR_SIZE]
{
int result[ARR_SIZE];
for (int i=0;i!=5;++i)
{
result[i]=(i+first);
}
decltype(result) *final_arr=&result;
return final_arr;
}
template <typename T>
void print_arr(T *beg, T *end)
{
cout << "[";
for (;beg!=end;++beg)
cout << *beg << ", ";
cout << "]" << endl;
}
int main()
{
decltype(arr) *a;
for (int i=1;i!=5;++i)
{
a=five(i);
print_arr(std::begin(*a),std::end(*a));
}
return 0;
}
Basically I have a function that returns pointer to array and I would like to print the contents of this array. I would expect this code to print four arrays:
[1,2,3,4,5]
[2,3,4,5,6]
[3,4,5,6,7]
[4,5,6,7,8]
However content of the printed arrays seems random. I would be greatful for a hint on what is wrong with the code.
Upvotes: 0
Views: 84
Reputation: 16070
You are going into undefined behaviour. You return a dangling pointer in five
.
int result[ARR_SIZE];
life-time is limited by scope of five
, therefore it gets freed at the end. Taking its address and returning it does not prolong its life.
This decltype(result) *final_arr=&result;
effectively doesn't do anything except hiding the error. You could have skipped it and write return &result;
which would most probably upset compiler seriously enough to not compile the code.
Upvotes: 3
Reputation: 16695
Your code produces undefined behavior - returning dangling pointer from five
function - it means you are returning a pointer which points to an object, which is allocated on the stack.
Upvotes: 2