D
D
Daniel2018-10-20 21:16:36
C++ / C#
Daniel, 2018-10-20 21:16:36

Why does the program break when memory is freed?

This is what the cut code looks like,
readLine() returns new char[length] . Then I'm going to release the memory and everything will crash, and if you don't delete it (remove delete [] ), then there will be a leak.
What could be wrong

void run(SocketListener* _this) {
  char *ret = NULL;
  try {
    for (;;) {
      ret = _this->readLine(); // вернет new char[len];
      if (ret == NULL) break;
      std::cout << ret;
      _this->getSocket()->send(response, lenResponse);

      delete[]ret;  // !!!!!!!!!!!!!!! ЛОМАЕТСЯ
    }
    //	} while (reads_bytes > 0 /*&& len==reads_bytes*/);

  }
  catch (std::runtime_error & err) {
    //std::cout << "ERROR  "<<err.what() << std::endl;
    if (ret != NULL) delete[]ret;
  }
  delete[] buf;
}
char * _Interface_Socket::readLine()
{
  std::string line = "";
  char buf[1];
  try {
    do {
      int reads_bytes = socket->recv(buf, 1);
      if (reads_bytes < 1) return NULL;
      line.push_back(buf[0]);

    } while (buf[0] != '\n');
  }
  catch (std::runtime_error &err) {
    status = false;
    return NULL;
  }
  char *response = new char[line.size()];
  std::strcpy(response, line.c_str());
  return response;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2018-10-20
@daniil14056

Why does the program break when memory is freed?

Because during operation, someone got out of the allocated memory and overwrote the service information in the heap. The easiest way to debug this is by running the program under valgrind.
But in this matter, everything is simpler:
char *response = new char[line.size()];
  std::strcpy(response, line.c_str());

Must bechar *response = new char[line.size() + 1];

V
Vitaly, 2018-10-20
@vt4a2h

For starters, I would remove the explicit use of new/delete. It's still C++. You have a std::string class, and use it everywhere (for example, when returning values). This class provides a reserve method to allocate the required amount of memory. It has a data method if it is necessary to pass a char* to the C API.
It is possible that you do not have a crash, but the program just hangs on send / post, waiting for a response. This is also worth checking out.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question