-3

I am pretty confused by the output of following code:

#include <cmath>
#include <vector>
#include <iostream>

class V
{
    std::vector<int> *ex_;
    
    public: 
        V( std::vector<int>::size_type sz );
        ~V();
};
    
V::V( std::vector<int>::size_type sz )
{
    // Why this doesn't work ??
    ex_ = new std::vector<int>( sz );
    std::cout<< "Ex size:" <<ex_->size() << std::endl;
}

V::~V()
{
    delete ex_;
}

int main()
{
  // This works 
  std::vector<int> *myVec = new std::vector<int>(10);
  std::cout << "Vector size:" << myVec->size() << std::endl;
  delete myVec;
  
  // Why this doesn't work ??
  V v(myVec->size());
  return 0;
}

Output:

Vector size:10

Ex size:34087952

http://ideone.com/WbCxaR

I had expected Ex size to be 10 and not the address of heap memory where vector is created on heap. What is it I am doing wrong here ?

trincot
  • 317,000
  • 35
  • 244
  • 286
nurabha
  • 1,152
  • 3
  • 18
  • 42
  • 2
    `myVec` has been deleted by the time you do this: `V v(myVec->size());`. But why are you using pointers and `new` at all? You really don't need to. – juanchopanza Feb 19 '15 at 08:25
  • "What is it I am doing wrong here" - invoking undefined behavior. You're dereferencing a dangling pointer. The object it addressed has been deleted. – WhozCraig Feb 19 '15 at 08:26
  • Well, this was a stupid question to ask. I wasnt noticing – nurabha Feb 19 '15 at 09:13

1 Answers1

2

Just because you are trying to get size from already freed pointer. It's not correct, delete myVec only after v construction.

Actually there is no need of pointer at all in this program.

ForEveR
  • 55,233
  • 2
  • 119
  • 133