Re: Unexpected -Wformat-truncation warnings

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

 



On 02/03/2018 16:43, Jonathan Wakely wrote:

> On 2 March 2018 at 15:00, Mason wrote:
>
>> On 02/03/2018 15:38, Jonathan Wakely wrote:
>>
>>> On 2 March 2018 at 14:27, Mason wrote:
>>>
>>>> I am confused by both of these warnings.
>>>> I am aware that adding two 60-char strings might overflow an 80-char buffer,
>>>> which is why I'm using snprintf.
>>>
>>> In which case the output would be truncated instead of overflowing,
>>> and that's what the warning says.
>>>
>>>> I'm not sure these warnings are very helpful. What am I missing?
>>>> (I may have oversimplified the testcase.)
>>>
>>> I think the point is that although you avoid undefined behaviour, you
>>> might still not get the output you expected.
>>
>> To provide some context, I am using the following struct:
>>
>> struct expr
>> {
>>         int val;
>>         char txt[60];
>> };
>>
>> to store symbolic arithmetic expressions.
>>
>> I start with simple symbolic constants "a", "b", "c", etc
>> and build up more complex expressions, such as "(a + b)" and "((a + b) * c)"
>>
>> Actual code, for example,
>>
>>         struct expr bak = tab[i];
>>         snprintf(tab[i].txt, 60, "(%s + %s)", bak.txt, tab[j].txt);
>>
>> Is there a different way to write this code to avoid the warning(s) or should
>> I just disable Wformat-truncation?
>> (I hate disabling warnings, but this one looks irrelevant, in my situation.)
> 
> I would have hoped that either assert(strlen(p->txt) < 40) or if
> (strlen(p->txt) >= 40) __builtin_unreachable(); would help, at least
> with optimizations enabled, but apparently not (and of course they can
> incur run-time cost).

According to perf, my program is spending most of its run-time in
stdio functions. I need to work on that :-)

    45.98%  a.out    libc-2.17.so       [.] vfprintf
    16.69%  a.out    libc-2.17.so       [.] _IO_default_xsputn
    12.40%  a.out    a.out              [.] step
     7.85%  a.out    libc-2.17.so       [.] __strchrnul
     3.63%  a.out    libc-2.17.so       [.] __vsnprintf_chk
     3.31%  a.out    libc-2.17.so       [.] _IO_str_init_static_internal
     2.83%  a.out    libc-2.17.so       [.] _IO_old_init
     2.51%  a.out    libc-2.17.so       [.] __GI___mempcpy
     1.21%  a.out    libc-2.17.so       [.] __snprintf_chk
     1.18%  a.out    libc-2.17.so       [.] _IO_no_init
     1.13%  a.out    libc-2.17.so       [.] _IO_setb
     0.80%  a.out    libc-2.17.so       [.] free
     0.38%  a.out    libc-2.17.so       [.] @plt
     0.10%  a.out    a.out              [.] __snprintf_chk@plt

Regards.



[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux