Local array scope

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • D. Susman

    #1

    Local array scope

    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

    #2
    Re: Local array scope

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

    Comment

    Working...