Memory Leak/Corruption of Heap

Hi all,

I am trying to do some review of some C++ topics that I feel I need a refresher on. The problem that I am having is that one of the class objects is being deleted before it should be, or at least I think that is the problem. I am using Microsoft Visual C++ 2010 Express. Each run of the program always goes to the following code. Can anyone point me in the right direction as to what is causing this? Any help is greatly appreciated.

pUserData 0x00804d98 const void *
extern "C" _CRTIMP int __cdecl _CrtIsValidHeapPointer(
const void * pUserData
)
{
if (!pUserData)
return FALSE;

if (!_CrtIsValidPointer(pHdr(pUserData), sizeof(_CrtMemBlockHeader), FALSE))
return FALSE;

return HeapValidate( _crtheap, 0, pHdr(pUserData) );
}

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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
#include <iostream>
#include <string>
#include <cstdlib>
#include <cmath>

using namespace std;

class Polynomial
{
	public:
		Polynomial();
		Polynomial(const Polynomial &);
		Polynomial(const double [], const int);
		~Polynomial();
		int getDegree() const;
		friend double evaluate(const Polynomial, double);
		friend void extractCoefficients(double* &, int &);
		friend void assignCoefficients(double*, int, Polynomial &);
		void operator =(const Polynomial &);
		friend Polynomial operator +(const Polynomial &, const Polynomial &);
		friend Polynomial operator -(const Polynomial &, const Polynomial &);
		friend Polynomial operator *(const Polynomial &, const Polynomial &);
		friend ostream& operator <<(ostream &, const Polynomial &);
	private:
		double *coefficients;
		int degree;
};

Polynomial::Polynomial() : degree(0)
{
	coefficients = new double[degree + 1];
	coefficients[0] = 0;
}
Polynomial::Polynomial(const Polynomial &poly) : degree(poly.getDegree())
{
	coefficients = new double[degree + 1];

	for(int index = 0; index < (degree + 1); index++)
		coefficients[index] = poly.coefficients[index];
}
Polynomial::Polynomial(const double coefs[], const int deg) : degree(deg)
{
	if(degree < 0)
	{
		char ch;
		cout << "Error: Illegal value for degree. Aborting program.\n";
		cin.get(ch);
		exit(1);
	}

	coefficients = new double[degree + 1];

	for(int index = 0; index < (degree + 1); index++)
		coefficients[index] = coefs[index];
}

Polynomial::~Polynomial()
{
	delete [] coefficients;
}

int Polynomial::getDegree() const
{
	return (degree);
}
double evaluate(const Polynomial poly, double num)
{
	double sum = 0;

	for(int index = 0; index < (poly.getDegree() + 1); index++)
		sum += (poly.coefficients[index] * pow(num, index));

	return sum;
}

void extractCoefficients(double* &coefs, int &deg)
{
	char ch;

	cout << "Enter the degree of the expression: ";
	cin >> deg;
	cout << endl;
	
	do
	{
		cin.get(ch);
	}while(ch != '\n');

	coefs = new double[deg + 1];

	cout << "Enter the coefficients of the expression. Enter 0 for a missing term.\n";
	for(int index = deg; index >= 0; index--)
		cin >> coefs[index];
	cout << endl;

	do
	{
		cin.get(ch);
	}while(ch != '\n');
}
void assignCoefficients(double *coefs, int deg, Polynomial &poly)
{
	poly.degree = deg;
	poly.coefficients = new double[poly.degree + 1];

	for(int index = 0; index < (deg + 1); index++)
		poly.coefficients[index] = coefs[index];
}

void Polynomial::operator =(const Polynomial &poly)
{
	degree = poly.getDegree();

	for(int index = 0; index < (degree + 1); index++)
		coefficients[index] = poly.coefficients[index];
}
Polynomial operator +(const Polynomial &lhs, const Polynomial &rhs)
{
	Polynomial temp;

	if(lhs.getDegree() > rhs.getDegree())
		temp.degree = lhs.getDegree();
	else
		temp.degree = rhs.getDegree();

	temp.coefficients = new double[temp.degree + 1];

	for(int index = 0; index < (temp.getDegree() + 1); index++)
	{
		if(index == lhs.getDegree())
		{
			temp.coefficients[index] = lhs.coefficients[index] + rhs.coefficients[index];
			index++;

			while(index <= rhs.getDegree())
			{
				temp.coefficients[index] = rhs.coefficients[index];
				index++;
			}
		}
		else if(index == rhs.getDegree())
		{
			temp.coefficients[index] = lhs.coefficients[index] + rhs.coefficients[index];
			index++;

			while(index <= lhs.getDegree())
			{
				temp.coefficients[index] = lhs.coefficients[index];
				index++;
			}
		}
		else
		{
			temp.coefficients[index] = lhs.coefficients[index] + rhs.coefficients[index];
		}
	}

	return temp;
}
Polynomial operator -(const Polynomial &lhs, const Polynomial &rhs)
{
	Polynomial temp;

	if(lhs.getDegree() > rhs.getDegree())
		temp.degree = lhs.getDegree();
	else
		temp.degree = rhs.getDegree();

	temp.coefficients = new double[temp.degree + 1];

	for(int index = 0; index < (temp.getDegree() + 1); index++)
	{
		if(index == lhs.getDegree())
		{
			temp.coefficients[index] = lhs.coefficients[index] - rhs.coefficients[index];
			index++;

			while(index <= rhs.getDegree())
			{
				temp.coefficients[index] = rhs.coefficients[index];
				index++;
			}
		}
		else if(index == rhs.getDegree())
		{
			temp.coefficients[index] = lhs.coefficients[index] - rhs.coefficients[index];
			index++;

			while(index <= lhs.getDegree())
			{
				temp.coefficients[index] = lhs.coefficients[index];
				index++;
			}
		}
		else
		{
			temp.coefficients[index] = lhs.coefficients[index] - rhs.coefficients[index];
		}
	}

	return temp;
}
Polynomial operator *(const Polynomial &lhs, const Polynomial &rhs)
{
	Polynomial temp;

	temp.degree = lhs.getDegree() + rhs.getDegree();
	temp.coefficients = new double[temp.degree + 1];

	for(int index = 0; index < (temp.degree + 1); index++)
		temp.coefficients[index] = 0;

	for(int i = 0; i < (lhs.getDegree() + 1); i++)
	{
		for(int j = 0; j < (rhs.getDegree() + 1); j++)
			temp.coefficients[i + j] += lhs.coefficients[i] * rhs.coefficients[j];
	}

	return temp;
}
ostream& operator <<(ostream &ostr, const Polynomial &poly)
{
	ostr << poly.coefficients[poly.getDegree()];

	if(poly.getDegree() > 1)
		ostr << "x^" << poly.getDegree();
	else if(poly.getDegree() == 1)
		ostr << "x";

	for(int index = poly.getDegree() - 1; index >= 0; index--)
	{
		if(index == 0)
		{
			if(poly.coefficients[index] < 0)
				ostr << " - " << fabs(poly.coefficients[index]);
			else if(poly.coefficients[index] > 0)
				ostr << " + " << poly.coefficients[index];
		}
		else if(index == 1)
		{
			if(poly.coefficients[index] < -1)
				ostr << " - " << fabs(poly.coefficients[index]) << "x";
			else if(poly.coefficients[index] == -1)
				ostr << " - x";
			else if(poly.coefficients[index] == 1)
				ostr << " + x";
			else if(poly.coefficients[index] > 1)
				ostr << " + " << poly.coefficients[index] << "x";
		}
		else
		{
			if(poly.coefficients[index] < -1)
				ostr << " - " << fabs(poly.coefficients[index]) << "x^" << index;
			else if(poly.coefficients[index] == -1)
				ostr << " - x^" << index;
			else if(poly.coefficients[index] == 1)
				ostr << " + x^" << index;
			else if(poly.coefficients[index] > 1)
				ostr << " + " << poly.coefficients[index] << "x^" << index;
		}
	}

	return ostr;
}

bool finished();

int main()
{
	//int lhsDeg(1), rhsDeg(1), deg;
	//double lhsCoefs[] = { -4, 3 }, rhsCoefs[] = { 2, 6 };

	int deg;
	double *coefs;

	Polynomial p1, p2, p3;

	do
	{
		system("cls");
		extractCoefficients(coefs, deg);
		assignCoefficients(coefs, deg, p1);

		extractCoefficients(coefs, deg);
		assignCoefficients(coefs, deg, p2);

		cout << "Addition\n";
		p3 = p1 + p2;
		cout << p3 << endl;
		cout << "Evaluation: " << evaluate(p3, 5) << endl << endl;

		cout << "Subtraction\n";
		p3 = p1 - p2;
		cout << p3 << endl;
		cout << "Evaluation: " << evaluate(p3, 5) << endl << endl;

		cout << "Multiplication\n";
		p3 = p1 * p2;
		cout << p3 << endl;
		cout << "Evaluation: " << evaluate(p3, 5) << endl << endl;

	}while(!finished());

	return 0;
}

bool finished()
{
	string str;

	do
	{
		cout << "Would you like to repeat the program? (Y/N): ";
		getline(cin, str);

		if( (str.find_first_not_of("YyNn") != string::npos) || (str.length() > 1) )
			cout << "Response entered is not valid.\n";

	}while( (str.find_first_not_of("YyNn") != string::npos) || (str.length() > 1) );

	cout << endl;

	if(str.find_first_of("Yy") != string::npos)
		return false;

	return true;
}
> The problem that I am having is that one of the class objects is being deleted before it should be,
> or at least I think that is the problem.
¿what makes you think that?

Running your problem through valgrind
==31312== Invalid write of size 8
==31312==    at 0x4013E3: Polynomial::operator=(Polynomial const&) (foo.cpp:115)
==31312==    by 0x4020EA: main (foo.cpp:288)
==31312==  Address 0x5a85d28 is 0 bytes after a block of size 8 alloc'd
==31312==    at 0x4C2AC10: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==31312==    by 0x400F6A: Polynomial::Polynomial() (foo.cpp:31)
==31312==    by 0x402048: main (foo.cpp:276)

The code that refers to
1
2
3
4
5
6
7
void Polynomial::operator =(const Polynomial &poly)
{
	degree = poly.getDegree(); //changed the `size' of the array, but do not reallocate

	for(int index = 0; index < (degree + 1); index++)
		coefficients[index] = poly.coefficients[index]; //out of bounds
}
When you do Polynomial p3; you reserve enough space just for one coefficient. Then in the assignment you simplly write to memory that you don't own.


Also, {assign,extract}Coeficients() are leaking memory as you simply do coefs = new double[degree+1]; but you didn't deallocate the previous memory.
Thank you for your help ne555. I added

 
coefficients = new double[degree + 1];


to my overloaded assignment function and it fixed the problem. But my question now is, what is the difference between my assignment function and copy constructor, since they both have the same code? Thank you again for your help.
> But my question now is, what is the difference between my assignment function and copy constructor,
> since they both have the same code?
your assignment operator leaks memory and breaks with self-assignment.

http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom
Topic archived. No new replies allowed.