1

I'm new to C++ and I have some problem with memory allocation.

vector<int *> V;  

for(int i=0;i<3;i++){   
    int A[3];    
    cin>>A[0]>>A[1]>>A[2];  
    V.push_back(A);
}

for(int i=0;i<3;i++){
    cout<<V[i][0]<<V[i][1]<<V[i][2]<<endl;
}

I want to create arrays and push them into vector as below. But if I input

1 1 1
2 2 2
3 3 3

The output will be

3 3 3
3 3 3
3 3 3

If I replace int A[3] with int *A=new int() then I get the right answer. I want to know why?

3
  • 1
    you are storing a reference(through a pointer) to a local array Commented Mar 11, 2014 at 5:05
  • and that reference is not valid after execution of ending brace of for loop Commented Mar 11, 2014 at 5:08
  • yes I think I get the answer Commented Mar 11, 2014 at 6:00

2 Answers 2

1

When you use int A[3]; you are invoking undefined behaviour because the array you are storing in the vector goes out of scope after the loop.

If you use int *A = new int();, you are allocating one integer, and then using three, which is also invoking undefined behaviour.

You should be using int *A = new int[3]; or thereabouts to allocate an array of three int.


In the cold light of morning, the int *A = new int[3]; solution leaks horribly. The vector destructor doesn't know it needs to free the sub-arrays.

The diagnosis of the trouble remains accurate; the appropriate remedy needs rethinking.

I need to work on what the correct (leak-free) solution is — and I've got other things to do right now. One plausible option is vector< vector<int> >, but I've not coded that up so it works yet.

Sign up to request clarification or add additional context in comments.

2 Comments

I am still confused about the difference between int A[3] and int *A=new int[3]. I think they both allocate memory for 3 integer to the pointer A??
@user3404498 Yes, int A[3] allocate memory, but because of the life time of var A[3], the memory will be deallocated when goes out of the for loop.
0

Although their both generate a array with 3 element, their memory space are maintained in different behave.

int A[3] will generate a local array which will be destroyed after loop. Hence, the array in the vector is destroyed and you will get a strange result.

For int *A=new int[3], the array will not be destroyed until the delete operator is used. Hence all data in the vector will be hold corrected.

1 Comment

nice!I thoroughly understand this issue/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.