Search code examples
cerror-handlingprintftr24731

sprintf_s with a buffer too small


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).

char buffer[10];    
int length = sprintf_s( buffer, 10, "1234567890.1234567890." ); 

How do I catch this error so I can report it instead of crashing my application?

Edit:

After reading the comments below I went with _snprintf_s. If it returns a -1 value then the buffer was not updated.

length = _snprintf_s( buffer, 10, 9, "123456789" );
printf( "1) Length=%d\n", length ); // Length == 9

length = _snprintf_s( buffer, 10, 9, "1234567890.1234567890." );
printf( "2) Length=%d\n", length ); // Length == -1

length = _snprintf_s( buffer, 10, 10, "1234567890.1234567890." );
printf( "3) Length=%d\n", length ); // Crash, it needs room for the NULL char 

Solution

  • 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 */
    }