[Spice-devel] [PATCH usbredir] Avoid format truncation warnings on newer gcc

Jonathon Jongsma jjongsma at redhat.com
Fri Jul 28 16:07:46 UTC 2017


For some reason, newer versions  of gcc (e.g. 7.1.1 in fedora 26) print
a warning about format truncation even when using snprintf:

  CC       usbredirparser.lo
../../usbredirparser/usbredirparser.c: In function ‘usbredirparser_do_read’:
../../usbredirparser/usbredirparser.c:270:33: error: ‘%s’ directive output may be truncated writing up to 287 bytes into a region of size 64 [-Werror=format-truncation=]
     snprintf(buf, sizeof(buf), "%s", hello->version);
                                 ^~
../../usbredirparser/usbredirparser.c:270:5: note: ‘snprintf’ output between 1 and 288 bytes into a destination of size 64
     snprintf(buf, sizeof(buf), "%s", hello->version);
     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Because type_header is a 288-byte array that is cast to a 'struct
usb_redir_hello_header' and passed to the function, gcc apaprently believes
that hello->version might be up to 288 bytes and warns about format truncation.
To avoid this warning, simply use strncpy (and ensure that the last byte is
NULL).
---
 usbredirparser/usbredirparser.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/usbredirparser/usbredirparser.c b/usbredirparser/usbredirparser.c
index 5dfeb9e..8f239cc 100644
--- a/usbredirparser/usbredirparser.c
+++ b/usbredirparser/usbredirparser.c
@@ -267,7 +267,8 @@ static void usbredirparser_handle_hello(struct usbredirparser *parser_pub,
 
     /* In case hello->version is not 0 terminated (which would be a protocol
        violation)_ */
-    snprintf(buf, sizeof(buf), "%s", hello->version);
+    strncpy(buf, hello->version, sizeof(buf));
+    buf[sizeof(buf)-1] = '\0';
 
     memset(parser->peer_caps, 0, sizeof(parser->peer_caps));
     if (data_len > sizeof(parser->peer_caps)) {
-- 
2.13.3



More information about the Spice-devel mailing list