function returning pointer of its local vairable

Can some body please help me understand the output of this c++ programs , its giving erratic results
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <cstdio>
#include<iostream>
using namespace std;

float* area ( float radius );  

int main()
{
float rad = 1;
float *ar;
ar = area(rad);
cout<<(*ar);
cout<<" "<<(*ar);
cout<<endl;
cout<<(*ar);
cout<<"\n";
cout<<(*ar);
cout<<endl;
cout<<(*ar);
fflush(stdin);
cout<<" "<<(*ar);

}

float* area ( float radius )
{
float a=0;
float *areaPtr = &a;
a =  (3.14 * radius * radius);
return(areaPtr);
}


when I print the value of (*ar) it comes out different each time , the output is

3.14 1.85048e-38
2.26799e-38
0
1.85048e-38 0

Returning pointers and references to local objects or variables has undefined behavior because the data goes out of scope when the function returns. In other words, don't do it.
If behavior of returning address of local variable of a function is undefined then what is the use of a function returning pointer... like if a pointer is made global and used inside a function , or is passed to a function as one of its arguments and the function is doing manipulation at that address then it doesn't need to return that address.

Well you can return a pointer to data allocated from the free-store with new:

1
2
char* ptr = new char[1024];
return ptr;
Topic archived. No new replies allowed.