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