Why am I getting a "bunch of corruption"?

Please don't crucify me for this. I figured it would be nice to use char * because the string I was about to plot was of a known size. I also know that if timeinfo-> tm_hour returns something other than two digits, things will go badly wrong. However, when this function returns VIsual Studio, the monkey goes at me about HEAP CORRUPTION. Something went wrong? (Also, should I just use 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;
}

      

+2


a source to share


3 answers


You need to allocate one more byte, as .length

from string

returns its length without the terminating NUL, for which you also need a space in char*

.



those. suppose it Message.length()

returns 10. You allocate 21 bytes. Copy 11 buffers to a buffer, then copy a message that requires 10 bytes + one for NUL. Total: 22 bytes and you only have 21 allocations.

+7


a source


it

char* MessageBuffer = new char[Message.length()+11];

      

it should be

char* MessageBuffer = new char[Message.length()+12];

      



Since you are adding 11

an extra char to the buffer:

2 for hr
2 for ::
2 for min
2 for ::
2 for sec
1 for " "

      

you will need another one to complete the null

char.

+3


a source


As others have pointed out, the size MessageBuffer

should be increased by one.

However, instead of handling the raw char buffer in this way, you can simply pass the time information directly to _file

, without putting an intermediate string first. If you want in the intermediate line for some reason, I would assume you are using the class ostringstream

.

void writelogmessage(std::string Message)
{
    time_t rawtime;
    struct tm* timeinfo = 0;

    time(&rawtime);
    timeinfo = localtime(&rawtime);

    std::ostringstream stream;
    stream<<
        timeinfo->tm_hour<<"::"<<
        timeinfo->tm_min<<"::"<<
        timeinfo->tm_sec<<" "<<
        Message;

    _file<<stream.str();
}

      

+1


a source







All Articles