H
H
HentaiEtoIskusstvo2018-03-07 18:28:37
C++ / C#
HentaiEtoIskusstvo, 2018-03-07 18:28:37

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);
}

5aa004d8c8a83249300291.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
devalone, 2018-03-07
@HentaiEtoIskusstvo

Add a line ending character (has code 0) at the end of the line. It's also better to copy using strncpy

K
Kamil Khamitov, 2018-03-18
@Kobalt_x

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 question

Ask a Question

731 491 924 answers to any question