On 08/12/2014 04:25 AM, Joseph S. Myers wrote: > On Sun, 10 Aug 2014, Chen Gang wrote: > >> For "[%d]" in sprintf(), theoretically, the maximize size is 14 -- for >> 0x80000000, it is sizeof("[-2147483648]"). Normally, it may not cause >> real world bug, but if another issues occur, it may lead things worse. > > Negative values certainly don't make sense here, although it may still > make sense to be robust against them. If you get one, it probably means a > conversion from HOST_WIDE_INT to int has overflowed. > > int_size_in_bytes returns HOST_WIDE_INT (64-bit). I think the size > variable should be changed to HOST_WIDE_INT, buff expanded to be big > enough for any 64-bit value, and HOST_WIDE_INT_PRINT_DEC used in the > sprintf format. >
OK, thanks, what you said sounds reasonable to me. > Separately, I think it's generally a good idea to convert sprintf uses in > GCC to snprintf - checking in each case that the size is such that > truncation shouldn't occur, but snprintf provides extra safety in case > there is some problem with the size calculation (although there may also > be a case for having an snprintf variant with an assertion that no > truncation occurs, so that the compiler safely aborts rather than either > continuing on truncation or overflowing a buffer). > For me, if buffer is already enough, sprintf() is more obvious than snprintf() which let readers know about it should have no truncation, although what you said about snprintf() is true to me. Welcome additional disccusions or completions, and if no any additional reply within 1 week, I shall send patch v2 for it (still use sprintf). Thanks. -- Chen Gang Open share and attitude like air water and life which God blessed