Out of range exception thrown when declaring a C++ vector on the free store

117 views Asked by At

I'm working on a problem from Stroustrup's PPP book, Chapter 17 - the Drill. I keep getting out of range errors thrown and believe I may be accessing the vector m_vec incorrectly when I am initializing its values. I have tried both '*' and '&' operators with the vector declared [[with size = 10]] but get errors like C6200 Index '4' is out of range '0' to '1' for non-stack buffer 'm_vec'.

Here is my code - can anyone help out please --

#include <iostream>
#include <vector>

void print_array10(std::ostream &os, int *a, int n);
void print_vector(std::ostream &os, std::vector<int> vec1);

int main()
{
    using std::cout;
    using std::endl;
    using std::vector;

    //create the ostream for printing
    std::ostream os(std::cout.rdbuf());

    // allocate a vector of int on the free store and initialize it

    vector<int>* m_vec = new vector<int>( 10 );
                    // vector<Type> *vect = new vector<Type>(integer); allocates the vector size
                    // with everything on the free store (except vect pointer, which is on the stack).


    // initialize the vector with integers starting at 100
    for (int i = 0; i <= 9; ++i) {
        m_vec->push_back(1);
        m_vec[i] = { i };
    };

    cout << &m_vec[4] << endl;
    cout << "  " << m_vec->size() << endl;



    //print_vector(os, *m_vec);

    delete m_vec;
    return 0;
};


// create print_vector function
void print_vector(std::ostream &os, std::vector<int> vec1) {
    for (int i = 0; i < 10; i++)
        std::cout << vec1[i] << std::endl;
};

I got the array portion of this Drill working and was able to access the array (on the free store) with either the pointer // dereference // or [] subscript operators. When I try the same approach on this vector declared on the free store I get "out of range" exceptions at runtime.

What is the "non-stack" buffer associated with the vector I created on the free store? How can I fix this?

I also get some occasional error message advising that I'm using a 32 bit integer in a 16 bit space... which I don't really understand given the code above. It occurs when I add 100 to 'i' in the for loop to initialize the vector. Any ideas on this... I thought integers were all 32 bits.

Thanks for any help.

1

There are 1 answers

7
Cornel On

Don't use new keyword for vector. Its elements are on the heap/free store always. Look up documentation for vectors and examples on how to initialize them. Also, I'd suggest moving your three using statements outside and above the main function.