So my professor assigned us the task of making our own vector class, and I'm having an issue with the member function reserve() or possibly with my constructor that passes two arguments. The error I get is...
Unhandled exception at 0x775815de in IntVector2.exe: 0xC0000005: Access violation writing location 0xcccccccc.
The code is as follows, I'm new to this and any help or advice would be appreciated. I did search the forums for similar problems, and the internet, but couldn't find anything. I'm using Visual C++ 2008. I've also commented out a couple of member functions in the header file that I havn't started working on yet.
If I forgot to include anything please let me know, thanks again!
class IntVector
{
public:
//typedef T * iterator;
//typedef T value_type;
//constructors
IntVector();
IntVector(const IntVector & v); //copy constructor
IntVector & operator=(const IntVector & v); //
IntVector(unsignedint, int);
~IntVector();
//member functions
void clear();
unsignedint size() const;
bool empty() const;
unsignedint capacity() const;
void reserve(unsignedint);
void resize(unsignedint);
void resize(unsignedint, int);
int front() const;
int back() const;
void pop_back();
void push_back(int);
//iterator begin() const;
//iterator end() const;
//operator
int & operator[](unsignedint);
private:
unsignedint my_capacity; //int that holds the number of items that can be stored in the buffer
unsignedint my_size; // int that holds the number of items that are actually in the vector
int * buffer; //buffer is a pointer to a type T[Template]
};
IntVector::IntVector(unsignedint n, int x)
{
my_capacity = n;
my_size = n;
for (unsignedint i = 0; i < my_size - 1; i++)
buffer[i] = x;
}
void IntVector::reserve(unsignedint n)
{
if (buffer == 0)
{
my_size = 0;
my_capacity = 0;
}
if (my_capacity >= n) //returns if the current capacity is already larger than the one being asked for
return;
int * oldbuffer = buffer; //creates a pointer type int called oldbuffer that is a copy of the current buffer
buffer = newint[n];
if (buffer == 0)
return; //returns if the new buffer is equal to 0
for (unsignedint i = 0; i < my_size; i++) //loop that copies the old values in the buffer to the new buffer
buffer[i] = oldbuffer[i];
delete [] oldbuffer; //deletes the memory allocation of the old buffer
my_capacity = n; //sets the capacity size to the new value
}
Thank you both for the reply, I will see about reworking my constructor to allocate memory for the buffer and then let you know what happens, appreciate the advice.