I am implementing a vector for an exercise.
I want to do the following:
Initially allocate
100elements without calling it’s constructors. Whenever an object is added to the vector, it call it’s constructor until the vector is too large so that can’t contain all objects. When the vector is full I allocate other100objects, and so on.
This is the code:
#include <iostream>
#include <memory>
#include <exception>
#include <cstdarg>
using namespace std;
class indexOutOfBounds:exception
{
const virtual char* what()
{
return "Index out of bounds";
}
};
template <class T>
class Vector
{
private:
T* data;
allocator<T> data_all;
int length;
int _size;
public:
static const int block=100; // the size of a single allocation block
Vector()
{
data=data_all.allocate(block,NULL);
length=0;
_size=block;
}
Vector(int n,...)
{
va_list vl;
T temp;
va_start(vl, n);
for(int i=0; i<n;i++)
{
temp=va_arg(vl,T);
push_back(temp);
}
va_end(vl);
}
int size() const
{
return length;
}
void push_back(T item)
{
length++;
if(length==_size)
{
_size+=block;
data=data_all.allocate(_size,data);
}
data_all.construct(&data[length-1],item);
}
T& operator[] (int i) throw()
{
if(i<0 || i>=length)
throw indexOutOfBounds();
return data[i];
}
~Vector()
{
for(int i=0; i<length;i++)
{
data_all.destroy(&data[i]);
}
data_all.deallocate(data,_size);
}
};
int main(int argc, char** argv)
{
Vector<int> v(1,0);
cout << v[0] << endl;
return 0;
}
I get the exception when I try to print v[0]:
EXC_BAD_ACCESS(code=1, address= 0x0)
Maybe &v[0] is NULL, but I can’t figure the reason. If I don’t use the constructor with va_list and I just write a main like this:
int main(int argc, char** argv)
{
Vector<int> v;
v.push_back(1);
cout << v[0] << endl;
return 0;
}
I don’t get any exception. Can someone explain why?
The most probable reason is that in the constructor with variable arguments, you do not initialize
lengthor_size. This means that those values might be anything when you callpush_back.If you would have run your application in a debugger, and examined those variables, it would have been obvious. I recommend that next time you have a crash of some sort, run it in a debugger and try to figure it out first, before asking here.