bug-mes
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

memory corruption when printing large integers


From: Michael Forney
Subject: memory corruption when printing large integers
Date: Wed, 10 Apr 2024 14:32:46 -0700
User-agent: mblaze/1.2

I was debugging some memory corruption and tracked it down to ntoab.
Here's a minimal reproducer:

        #include <stdio.h>
        #include <stdlib.h>
        #include <string.h>

        int main(void) {
                char *s = malloc(16);
                strcpy(s, "abcdefghijklmno");
                printf("%lu\n", -1UL);
                printf("%s\n", s);
        }

This prints

        18446744073709551615
        abcdefg18446744073709551615

This happens because ntoab starts at offset 11 of a 20 byte buffer
and works backwards, but it may need as many as 22 bytes for a
64-bit value assuming base is at least 10 (1 for sign, 20 for value,
1 for nul). Since there are only 11 bytes available before the
starting offset, it ends up writing into the memory the program
allocated for its own string. Additionally, since the pointer is
temporarily decremented once more, one extra byte is needed to avoid
undefined behavior.

Here's my suggested fix:
1. Increase __itoa_buf size to 23.
2. Initialize p to __itoa_buf + 22.
3. Adjust the assert to check that base >= 10.

I believe that no bases below 10 are used, but if they are, __itoa_buf
would need to increase to 67, and the starting p offset to 66.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]