understanding the dangers of sprintf(…)

前端 未结 8 1437

OWASP says:

\"C library functions such as strcpy (), strcat (), sprintf () and vsprintf () operate on null terminated strings and perform no bou

8条回答
  •  渐次进展
    2020-12-01 05:17

    It is very important to remember that sprintf() adds the ASCII 0 character as string terminator at the end of each string. Therefore, the destination buffer must have at least n+1 bytes (To print the word "HELLO", a 6-byte buffer is required, NOT 5)

    In the example below, it may not be obvious, but in the 2-byte destination buffer, the second byte will be overwritten by ASCII 0 character. If only 1 byte was allocated for the buffer, this would cause buffer overrun.

    char buf[3] = {'1', '2'};
    int n = sprintf(buf, "A");
    

    Also note that the return value of sprintf() does NOT include the null-terminating character. In the example above, 2 bytes were written, but the function returns '1'.

    In the example below, the first byte of class member variable 'i' would be partially overwritten by sprintf() (on a 32-bit system).

    struct S
    {
        char buf[4];
        int i;
    };
    
    
    int main()
    {
        struct S s = { };
        s.i = 12345;
    
        int num = sprintf(s.buf, "ABCD");
        // The value of s.i is NOT 12345 anymore !
    
        return 0;
    }
    

提交回复
热议问题