Custom "String" class problem(s)

Hello!

I am currently working on a custom "String" class in C++ for a project.

When I just use ONE String, it works fine. However, when I try to create an array (using std::vector) of them, the following error occurs:
_BLOCK_TYPE_IS_VALID(pHead->nBlockuse)
As I understand it, this means that I somehow freed memory twice. If this is correct, I really can't find the location.

The relevant code is as follows:
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
uint32 GetStringSize(const char* str)
{
	for (uint16 i = 0; i < 10001; i++)
	{ if (str[i] == '\0') { return i; } }

	return 0;
}

class String
{
private:
	char* str;
	char errVal;
	uint16 size;

public:
	String();
	String(const char* string);
	~String();

	operator const char*();
	char& operator[](uint16 index);
};

String::String():
	str(new char[1]), size(0) { }

String::String(const char* string)
{
	size = GetStringSize(string);
	str = new char[size + 1];

	for (uint16 i = 0; i < size; i++)
	{ str[i] = string[i]; }

	str[size] = '\0';
}

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

String::operator const char*()
{ return str; }

char& String::operator[](uint16 index)
{
	if (index >= size)
	{
		errVal = '0';
		return errVal;
	}

	return str[index];
}


From what I can tell, when I use return String(...), it creates a new String object, returns a copy of it and then calls the destructor as it goes out of scope. Is this correct? If so, is this the problem?

I'd appreciate any help.
The String object will have to be copied when it's returned from the function so you have to implement the copy constructor and the copy assignment operator to handle copying correctly.
I don't understand how you mean. Could you give an example?
With your current code:

1
2
3
4
    String a;
    String b(a);
    String c;
    c = b;


a, b and c all have str members pointing to the same piece of memory, so when their respective destructors are called the same memory will be freed 3 times.

http://ideone.com/oT9huu
the vector will copy the string which you push,that is it will call the default copy constructor,String::String,so you should implement the default copy constructor
double delete,one is you delete and the other is vector delete
Thank you, I got it working now.
Last edited on
Topic archived. No new replies allowed.