Answer the question
In order to leave comments, you need to log in
When copying data from one array to another, the last element is copied with garbage values. How to fix it?
String::String() {
m_length = 80;
m_capacity = 160;
m_str = new char[m_length] {};
}
void String::setStr(char* str) {
if (m_length < strlen(str)) {
return;
}
else {
if (str != nullptr) {
for (int i = 0; i < strlen(str); ++i) {
m_str[i] = str[i];
}
}
}
}
void String::ShrinkToFit() {
String str;
str.setStr(m_str);
m_str = nullptr;
delete[] m_str;
m_str = new char[strlen(str.m_str)];
setStr(str.m_str);
}
Answer the question
In order to leave comments, you need to log in
Add a line ending character (has code 0) at the end of the line. It's also better to copy using strncpy
Are you sure that the memory does not get corrupted in your setStr () copying only if the length of the string > length of the buffer, and you copy the entire string in its entirety, simultaneously creating memory corruption. Well, about the \0 character you have already written above. In general, there is strdup () but it is outside the standard.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question