sprintf_s with a buffer too small

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

    Instead of sprintf_s, you could use snprintf (a.k.a _snprintf on windows).

    #ifdef WIN32
    #define snprintf _snprintf
    #endif
    
    char buffer[10];    
    int length = snprintf( buffer, 10, "1234567890.1234567890." );
    // unix snprintf returns length output would actually require;
    // windows _snprintf returns actual output length if output fits, else negative
    if (length >= sizeof(buffer) || length<0) 
    {
        /* error handling */
    }
    

提交回复
热议问题