質問

これについては私を十字架につけないでください。私が構築するつもりだった文字列は既知のサイズであるため、Char*を使用するのが良いかもしれないと判断しました。また、TimeInfo-> tm_hourが2桁以外のものを返している場合、事態はひどく間違っていることを知っています。とはいえ、この機能がVisual Studioを返すと、Heap Corruptionについて猿になります。どうしたの? (また、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;
}
役に立ちましたか?

解決

それ以来、もう1つのバイトを割り当てる必要があります .lengthstring 終了nulなしでその長さを返します。 char*.

つまり、と思う Message.length() 返品10. 21バイトを割り当てます。 11バイトをバッファーにコピーしてから、メッセージをコピーします。メッセージをコピーします。これには、NULには10バイト + 1つが必要です。合計:22バイトで、21の割り当てしかありません。

他のヒント

これ

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

あるべきです

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

追加しているからです 11 バッファへの追加のchar:

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

終了には追加が必要です null char。

他の人が指摘したように、のサイズ MessageBuffer 1つ増やす必要があります。

ただし、そのように生のcharバッファーを扱うのではなく、時間情報を直接ストリーミングすることができます _file 最初に中間文字列に入れることなく。何らかの理由で中間文字列でそれを望むなら、私はあなたが 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();
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top