Local array scope

D

D. Susman

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;
}
 
K

Kai-Uwe Bux

D. Susman said:
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.

However, when I run the program, I get "2".

You dereference an invalid pointer. Anything can happen, including a value
of 2.
It seems to that I get this result by luck; in further executions, I may
get some other value. Am i right?
Yes.

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.
return 0;
}


Best

Kai-Uwe Bux
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top