Reputation: 1
I'm having a problem with it handling strings. Whenever I try a string, I get a lovely little error code:
Unhandled exception at 0x77e815de in arraytest.exe: 0xC0000005: Access violation reading location 0xabababab.
It handles int, double, and char just fine. I also tried the exact same test string I was using (the alphabet) as a char* and it did that fine too. It just pukes on strings, for a reason that I cannot quite fathom. I really don't know where to go with it next. Any suggestions?
Upvotes: 0
Views: 302
Reputation: 92311
You have a problem with your reallocation code in push_back
template<class type>
void DynamicArray<type>::push_back(type newValue)
{
++_size; // <=== **
if (_size > _capacity) // If size larger than capacity
{
_capacity *= CAPACITY_MULT; // double capacity
type* tempArray = new type[_capacity];// Create temporary array with new capacity
// Copy array values into temporary array
for (int i = 0; i < _size; i++) // <=== **
{
tempArray[i] = dynArray[i];
}
// Delete dynArray
delete[] dynArray;
// Insert new value at end of temporary array
// Set dynArray to temporary array
dynArray = tempArray;
}
dynArray[_size - 1] = newValue;
}
You start by increasing the size of the current container before checking if there is room for the new element. Then you use the new size when copying the old values to a new array.
This might seem to work for primitive types, but a std::string
will try to copy its own internal data (which isn't there) and liklely cause an access violation.
Upvotes: 3