Dynamic Array Class

Hi! I'm making a dynamic array class for an exercise but I'm having some trouble with my code. I'm getting something like 'there might be a corruption in the heap' or something. Here's the implementation of the class:

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include "ArrayClass.h"


ArrayClass::ArrayClass()
{
	mSize=0;
	mData=new float[0];
}


ArrayClass::~ArrayClass()
{
	delete[] mData;
	mData=0;
	
}

ArrayClass::ArrayClass(int size)
{
	mSize=size;
	mData=new float[mSize];
}

float& ArrayClass::operator[](int i)
{
	return mData[i];
}


int ArrayClass::size()
{
	
	return mSize;
}


ArrayClass::ArrayClass(const ArrayClass& rhs)
{
	int len=rhs.mSize;
	mData=new float[len];

	for(int i=0;i<rhs.mSize;++i)
	{
		mData[i]=rhs.mData[i];
	}

}


ArrayClass& ArrayClass::operator=(const ArrayClass& rhs)
{
	if(this==&rhs)
	{
		return *this;
	}


	delete[] mData;

	for(int i=0;i<rhs.mSize+1;++i)
	{
		mData[i]=rhs.mData[i];
	}

	return *this;
}


void ArrayClass::resize(int newSize)
{
	
	float* newArray=new float[newSize+1];

	if(newSize>=mSize)
	{
		for(int i=0;i<mSize;++i)
		{
			newArray[i]=mData[i];
		}
	}

	else if(newSize<mSize)
	{
		for(int i=0;i<newSize;++i)
		{
			newArray[i]=mData[i];
		}
	}

	
	mData=newArray;
	mSize=newSize;

	

}


What's wrong with it? Thanks a lot!
Don't make an array of size zero or confuse NULL with zero.
1
2
3
4
5
6
7
if (mSize <= 0)
  mData = NULL;
else
 mData = new float[mSize];

delete [] mData;
mData = NULL;


In your = operator, you delete mData and then start using it as if it wasn't deleted, this could be where your warning is coming from.
Last edited on
Thanks!

One question though, if I don't delete mData, then how do I free the memory previously stored in mData(if there was any).
Topic archived. No new replies allowed.