Skip to content

Commit 2ee2a0d

Browse files
Add null terminator to String implementation #7
1 parent 3ecc0a5 commit 2ee2a0d

1 file changed

Lines changed: 10 additions & 5 deletions

File tree

test/String.cpp

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,9 @@ namespace CPPShift {
2525
{
2626
this->mp = mp;
2727
this->length = strlen(str);
28-
this->start = new (mp) char[this->length];
28+
this->start = new (mp) char[this->length + 1];
2929
memcpy(this->start, str, this->length);
30+
this->start[this->length] = '\0';
3031
}
3132

3233
String::~String() { Memory::MemoryPoolManager::free(this->start); }
@@ -39,34 +40,38 @@ namespace CPPShift {
3940
{
4041
Memory::MemoryPoolManager::free(this->start);
4142
this->length = strlen(str);
42-
this->start = new (this->mp) char[this->length];
43+
this->start = new (this->mp) char[this->length + 1];
4344
memcpy(this->start, str, this->length);
45+
this->start[this->length] = '\0';
4446
return *this;
4547
}
4648

4749
String& String::operator=(const String& str)
4850
{
4951
Memory::MemoryPoolManager::free(this->start);
5052
this->length = str.size();
51-
this->start = new (this->mp) char[this->length];
53+
this->start = new (this->mp) char[this->length + 1];
5254
memcpy(this->start, str.data(), this->length);
55+
this->start[this->length] = '\0';
5356
return *this;
5457
}
5558

5659
String& String::operator+=(const char* str)
5760
{
5861
int add_length = strlen(str);
59-
this->start = (char*) Memory::MemoryPoolManager::reallocate(this->start, this->length + add_length);
62+
this->start = (char*) Memory::MemoryPoolManager::reallocate(this->start, this->length + add_length + 1);
6063
memcpy(this->start + this->length, str, add_length);
6164
this->length += add_length;
65+
this->start[this->length] = '\0';
6266
return *this;
6367
}
6468

6569
String& String::operator+=(const String& str)
6670
{
67-
this->start = (char*) Memory::MemoryPoolManager::reallocate(this->start, this->length + str.size());
71+
this->start = (char*) Memory::MemoryPoolManager::reallocate(this->start, this->length + str.size() + 1);
6872
memcpy(this->start + this->length, str.data(), str.size());
6973
this->length += str.size();
74+
this->start[this->length] = '\0';
7075
return *this;
7176
}
7277

0 commit comments

Comments
 (0)