Answer the question
In order to leave comments, you need to log in
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
Why does the program break when memory is freed?
char *response = new char[line.size()]; std::strcpy(response, line.c_str());
char *response = new char[line.size() + 1];
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 questionAsk a Question
731 491 924 answers to any question