sprintf_s with a buffer too small

后端 未结 6 1208
广开言路
广开言路 2021-02-08 12:03

The following code causes an error and kills my application. It makes sense as the buffer is only 10 bytes long and the text is 22 bytes long (buffer overflow).



        
6条回答
  •  说谎
    说谎 (楼主)
    2021-02-08 12:51

    From MSDN:

    The other main difference between sprintf_s and sprintf is that sprintf_s takes a length parameter specifying the size of the output buffer in characters. If the buffer is too small for the text being printed then the buffer is set to an empty string and the invalid parameter handler is invoked. Unlike snprintf, sprintf_s guarantees that the buffer will be null-terminated (unless the buffer size is zero).

    So ideally what you've written should work correctly.

提交回复
热议问题