Dynamic Array Constructors in Template Class

Hi, I believe my constructors are not correct. I keep getting this runtime error: invalid allocation size 4294967295 bytes. Can anyone identify the problem?

Here's the code to help you see what I'm working with:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
private:
    T* data;
    unsigned int capacity;
    unsigned int lastIndex;

template<class T>
DynamicArray<T>::DynamicArray(void) { //default constructor: makes an initial data array of size 10

	data = new T[10];
}

template<class T>
DynamicArray<T>::DynamicArray(unsigned int initial) { //constructor for a specific initial size
	
	if(initial > 0)
	{
		data = new T[initial];
	}
	else
	{
		data = NULL;
	}
	capacity = initial;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
template<typename T>
	class Dynamic
	{
		T* data;
		unsigned int size;
		unsigned int current;
		bool Valid(unsigned int loc)
		{
			if(loc < 0 || loc > size) return 0;
			else return 1;
		}
	public:
		Dynamic(unsigned int sz = 10): size(sz), current(sz-1)
		{
			data = new T[sz];
		}
		T& at(unsigned int loc)
		{
			if(!Valid(loc)) throw "Invalid location\n";
			else return data[loc];
		}
		void set(const T value, const unsigned int loc)
		{
			if(!Valid(loc)) throw "Invalid location\n";
			else data[loc] = value;
		}
		unsigned int getsize() { return size; }
		~Dynamic() { delete[] data; }
	};
Just a little addition: Why are you testing a size_t aka unsigned int against 0, the check is redundant because you can't possibly assign a negative digit to a size_t and get a negative digit in return. If you accidentally or intentionally give unsigned integer variable a negative value, your compiler would generate code for a signed int literal and then move that into your unsigned int literal space.

tl;dr Don't bother checking if a size_t is lesser than 0, because it always is greater
1
2
unsigned int x = -5;
int y = x; // y is not -5 but std::numeric_limits<int>::max() - 5. 
Last edited on
Topic archived. No new replies allowed.