For some reason I am unable to delete character pointers

It gives me a weird error where a pop up comes up and says "HEAD CORRUPTION DETECTED"

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
#include <iostream>
#include <cstring>

using namespace std;

class Text
{
private:
	int length;
	

public:
	char * str;
	Text(const char * STR);
	~Text();
};

Text::Text(const char * usertext)
{
	length = (strlen(usertext));
	str = new char[length];
	strcpy(str, usertext);
}

Text::~Text()
{
	delete []str;
}

int main()
{
	Text first("line 1");
	first.~Text();
	system("pause");
	return 0;
}
str = new char[length + 1 // for the terminator ;
Is that the \0 character? I thought that was automatically added in?
Last edited on
No it's not :)
Why are you not using std::string ?
Is that the \0 character? I thought that was automatically added in?


It is automatically copied by strcpy, but it's not included as part of the length.

Example:
strlen( "foo" );

This will give you 3, but the string "foo" actually consumes 4 bytes of memory (3 for the 'foo' and an extra 1 for the null terminator.

As a result...
1
2
Text first("line 1");  // this is allocating 6 bytes of memory... but then copying 7 bytes to that memory.
 //   So you are going out of bounds.  Hence the heap corruption. 




Also... DO NOT CALL DESTRUCTORS EXPLICITLY
1
2
3
4
int main()
{
	Text first("line 1");
	first.~Text();  // BAD BAD BAD 


Destructors are called automatically! That's the whole point. By doing this you're calling the dtor twice which is very dangerous.


EDIT:

Also, +1 @ Zaita. Use a string.
Last edited on
Topic archived. No new replies allowed.