Please don’t crucify me for this one. I decided it might be good to use a char* because the string I intended to build was of a known size. I am also aware that if timeinfo->tm_hour returns something other than 2 digits, things are going to go badly wrong. That said, when this function returns VIsual Studio goes ape at me about HEAP CORRUPTION. What’s going wrong? (Also, should I just use a stringbuilder?)
void cLogger::_writelogmessage(std::string Message)
{
time_t rawtime;
struct tm* timeinfo = 0;
time(&rawtime);
timeinfo = localtime(&rawtime);
char* MessageBuffer = new char[Message.length()+11];
char* msgptr = MessageBuffer;
_itoa(timeinfo->tm_hour, msgptr, 10);
msgptr+=2;
strcpy(msgptr, "::");
msgptr+=2;
_itoa(timeinfo->tm_min, msgptr, 10);
msgptr+=2;
strcpy(msgptr, "::");
msgptr+=2;
_itoa(timeinfo->tm_sec, msgptr, 10);
msgptr+=2;
strcpy(msgptr, " ");
msgptr+=1;
strcpy(msgptr, Message.c_str());
_file << MessageBuffer;
delete[] MessageBuffer;
}
You need to allocate one more byte, since
.lengthof astringreturns its length without the terminating NUL, for which you also need space in thechar*.I.e. suppose
Message.length()returns 10. You allocate 21 bytes. Copy 11 bytes into the buffer, then copy the message, which needs 10 bytes + one for NUL. Total: 22 bytes, and you only have 21 allocated.