using realloc with templates to make MyVector class

First off thanks for any help I can get here, I'm pulling my hair out in frustration with my lack of knowledge on this subject.

My professor has asked us to write a basic vector class, I had written one however it was using a set size T element[100] and he wants instead T *elements and for us to use realloc to constantly adjust the size of the vector. We have not learned about realloc and so I have only the description and example I found here, can someone please tell me why I'm getting an error on line 45 when I try to use this class:

#include <iostream>
#include <cstdlib>
using namespace std;

template<typename T>
class MyVector
{
public:
MyVector();
void push_back(T element);
void pop_back();
unsigned int size();
bool empty();
T at(int index);
void clear();
void swap(MyVector v2);

private:
T *elements;
int vectorSize;
};

template<typename T>
MyVector<T>::MyVector()
{
vectorSize = 0;
}

template<typename T>
bool MyVector<T>::empty()
{
return (vectorSize == 0);
}

template<typename T>
T MyVector<T>::at(int index)
{
return elements[index];
}

template<typename T>
void MyVector<T>::push_back(T value)
{
vectorSize++;
elements = (T *)realloc(elements,vectorSize * sizeof(T)); // PROBLEM!
elements[vectorSize - 1] = value;
}
What kind of error do you get?

Please use code tags: [code]Your code[/code]
It's definitely useful to be less vague than "I got an error."

In the code you show here, elements is never initialized to any value. std::realloc only works with a pointer to memory that has previously been allocated via malloc or calloc.

I would suggest, when constructing an empty vector, that elements is made to point to memory allocated by malloc . Even if you only allocate one byte, you've got the pointer from malloc you need to work with for realloc.

Food for thought: What should happen in pop_back? Maybe the concept of the amount of memory allocated should be separate from the number of elements in the container? If you do separate them, would it make more sense to realloc in larger chunks of memory so every push_back doesn't require a realloc?
Also, what is going to happen to elements if the realloc fails?
Unhandled exception at 0x771d15de in MyVector.exe: 0xC0000005: Access violation reading location 0xccccccc8.

Malloc and calloc?

Let me ask this, and I know its definitely a noob question but we just barely learned about classes and they are still new to me:

The private fields element and vectorSize, they are both going to be seperate for every vector created right? So I could initialize element to NULL in the standard constructor, and every single vector created would have its own seperate elements set to NULL, they wouldn't share the same elements and reset it to NULL correct?
Correct
Topic archived. No new replies allowed.