Connecting Tech Pros Worldwide Forums | Help | Site Map

Local array scope

D. Susman
Guest
 
Posts: n/a
#1: Jul 4 '08
Hi,

When the method "foo" ends, shouldn't the arr[2] array be gone (due to
scope termination) and the pointer in class A be invalid? However,
when I run the program, I get "2". It seems to that I get this result
by luck; in further executions, I may get some other value. Am i
right?
class A
{
public:
A( int* ptr ){ arr = ptr; }
int* getArr(){ return arr; }
private:
int* arr;
};

A foo( )
{
int arr[2] = {2,1};
return A( arr );
}

int main()
{
A a = foo();
int* arr = a.getArr();

cout << arr[0] << endl; // This is not ambigous, since arr has
actually gone out of scope, am i right?
return 0;
}

Kai-Uwe Bux
Guest
 
Posts: n/a
#2: Jul 4 '08

re: Local array scope


D. Susman wrote:
Quote:
Hi,
>
When the method "foo" ends, shouldn't the arr[2] array be gone (due to
scope termination) and the pointer in class A be invalid?
Yes.
Quote:
However, when I run the program, I get "2".
You dereference an invalid pointer. Anything can happen, including a value
of 2.
Quote:
It seems to that I get this result by luck; in further executions, I may
get some other value. Am i right?
Yes.
Quote:
class A
{
public:
A( int* ptr ){ arr = ptr; }
int* getArr(){ return arr; }
private:
int* arr;
};
>
A foo( )
{
int arr[2] = {2,1};
return A( arr );
}
>
int main()
{
A a = foo();
int* arr = a.getArr();
>
cout << arr[0] << endl; // This is not ambigous, since arr has
actually gone out of scope, am i right?
"Ambiguous" ????

It is undefined behavior. That's all.
Quote:
return 0;
}

Best

Kai-Uwe Bux
Closed Thread