Heap corruption error please help!

I am getting a heap corruption error from my code, I am only calling the constructor with "hello" in the parameter and then I am using cout with the getName function. Please tell me why I am getting heap corruption when I use delete [] charArray; in my .cpp file. without it the program runs fine but I have a memory leak. This is due tomorrow so help soon would be great.
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
//base class for shapes.
#include <iostream>
#include <string>
#include <cstring>
using namespace std;

#ifndef SHAPE_H
#define SHAPE_H

class shape
{

public:

	//constructor
	shape();
	shape(string);
	//destructor
	~shape();
	//accessors
	double getWidth();
	double getHeight();
	string getName();

	virtual void setWidth(double);
	virtual void setHeight(double);
	virtual void setName(string);
	virtual void calcArea();

private:
	char * charArray;
	double width;
	double height;
	double area;

};
#endif 

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

#include "shape.h"

shape::shape()
{
	charArray = new char[0]; //default 
}

shape::shape(string temp)
{
	charArray = new char[temp.size()];
	strcpy(charArray, temp.c_str());
}

string shape::getName()
{
	string temp = "";

	for(int i = 0; charArray[i] != 0; i++)
	{
		temp +=charArray[i];
	}

	return temp;
}
void shape::calcArea()
{
	area = height * width;
}

double shape::getHeight()
{
	return 0;
}

double shape::getWidth()
{
	return 0;
}

void shape::setHeight(double temp)
{

}

void shape::setWidth(double temp)
{

}

void shape::setName(string temp)
{
	strcpy(charArray, temp.c_str());
}

shape::~shape()
{
	delete [] charArray;
}


I have to use a char array because my teacher is making us. Thanks, Derek.
11
12
	charArray = new char[temp.size()];
	strcpy(charArray, temp.c_str());

You forgot to add room for the null character.
You're using strcpy incorrectly.

the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character)


strcpy(charArray, temp.c_str());

charArray, the destination, has to have enough space for all the letters AND the terminating null character.
http://cplusplus.com/reference/clibrary/cstring/strcpy/
Last edited on
Thanks a lot guys I completely forgot about the null char.
Topic archived. No new replies allowed.