Re: _stprintf



"Joseph M. Newcomer" <newcomer@xxxxxxxxxxxx> wrote in message news:e57oc2lrr2nd1j0nt83h8e7h02ahjsbqih@xxxxxxxxxx

Use CString::Format as the preferred choice.

On "real" Windows I agree. On Windows CE where extra libraries will occupy the machine's RAM, it might not be a good idea.

If you MUST use some form like _stprintf, use StringCchPrintf (I think that's the name, but search for strsafe.h on the MSDN) which at least will avoid any possibility of buffer overflow

As documented it will not have such a beneficial effect.

StringCchPrintf(_T("%c"), B, sizeof(B) / sizeof(TCHAR), (BYTE)('a' + i));

Mihai N. addressed a problem with your cast to BYTE and you made an adjustment which I'm still thinking about. Since arguments to StringCchPrintf are either Unicode or ANSI, the last argument should be either char or wchar_t, and I'm trying to figure out if WORD is guaranteed to marshall a char value properly.

More importantly is that, as documented, buffer overflow can very easily occur. Suppose we have an ANSI compilation and make B an array of 2 chars. Then the buffer has enough space for 1 single-byte character plus a null character. But if the last argument is a double-byte character then StringCchPrintf is documented to copy both bytes plus a single-byte null character, total 3 bytes.

.



Relevant Pages

  • Re: One problem or two?
    ... savefile is called [character name].saved_game. ... char filename; ... The filename will be 35 characters long, plus the null at the end, and 36 chars won't fit in an array designed for 32. ... If you are unlucky, it might damage a return address, and you have created an exploitable buffer overflow. ...
    (rec.games.roguelike.development)
  • Re: One problem or two?
    ... savefile is called [character name].saved_game. ... For your first problem this could look like: ... char filename; ... If you are unlucky, it might damage a return address, and you have created an exploitable buffer overflow. ...
    (rec.games.roguelike.development)
  • Re: doubly-linked list & sorting
    ... char Emess; ... diff = -1; ...
    (comp.lang.c)
  • Re: Mathematics of the Enigma cipher?
    ... A character is mapped to an integer which becomes ... All the Rotors should be advanced ... char val3=R2.GetCharacterIndex; ... I thought the Reflector was fixed. ...
    (comp.programming)
  • Re: Mathematics of the Enigma cipher?
    ... A character is mapped to an integer which becomes ... All the Rotors should be advanced ... char val3=R2.GetCharacterIndex; ... I thought the Reflector was fixed. ...
    (comp.programming)