sprintf_s with a buffer too small

后端 未结 6 1207
广开言路
广开言路 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:47

    This works with VC++ and is even safer than using snprintf (and certainly safer than _snprintf):

    void TestString(const char* pEvil)
    {
      char buffer[100];
      _snprintf_s(buffer, _TRUNCATE, "Some data: %s\n", pEvil);
    }
    

    The _TRUNCATE flag indicates that the string should be truncated. In this form the size of the buffer isn't actually passed in, which (paradoxically!) is what makes it so safe. The compiler uses template magic to infer the buffer size which means it cannot be incorrectly specified (a surprisingly common error). This technique can be applied to create other safe string wrappers, as described in my blog post here: https://randomascii.wordpress.com/2013/04/03/stop-using-strncpy-already/

提交回复
热议问题