From 86f158bc15cd63740131ca102179c760a691e4c8 Mon Sep 17 00:00:00 2001 From: Paul Eggert Date: Wed, 6 Jun 2012 22:11:51 -0700 Subject: [PATCH] * doprnt.c (doprnt): Truncate multibyte char correctly. Without this change, doprnt (buf, 2, "%s", FORMAT_END, AP) would mishandle a string argument "Xc" if X was a multibyte character of length 2: it would truncate after X's first byte rather than including all of X. --- src/ChangeLog | 8 ++++++++ src/doprnt.c | 22 +++++++++++++--------- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/src/ChangeLog b/src/ChangeLog index 7ea9ad8f3e3..3acf12e4483 100644 --- a/src/ChangeLog +++ b/src/ChangeLog @@ -1,3 +1,11 @@ +2012-06-07 Paul Eggert + + * doprnt.c (doprnt): Truncate multibyte char correctly. + Without this change, doprnt (buf, 2, "%s", FORMAT_END, AP) + would mishandle a string argument "Xc" if X was a multibyte + character of length 2: it would truncate after X's first byte + rather than including all of X. + 2012-06-06 Chong Yidong * buffer.c (word_wrap): Doc fix. diff --git a/src/doprnt.c b/src/doprnt.c index df9ebc11f9c..b106ffb1938 100644 --- a/src/doprnt.c +++ b/src/doprnt.c @@ -392,15 +392,19 @@ doprnt (char *buffer, ptrdiff_t bufsize, const char *format, { /* Truncate the string at character boundary. */ tem = bufsize; - while (!CHAR_HEAD_P (string[tem - 1])) tem--; - /* If the multibyte sequence of this character is - too long for the space we have left in the - buffer, truncate before it. */ - if (tem > 0 - && BYTES_BY_CHAR_HEAD (string[tem - 1]) > bufsize) - tem--; - if (tem > 0) - memcpy (bufptr, string, tem); + do + { + tem--; + if (CHAR_HEAD_P (string[tem])) + { + if (BYTES_BY_CHAR_HEAD (string[tem]) <= bufsize - tem) + tem = bufsize; + break; + } + } + while (tem != 0); + + memcpy (bufptr, string, tem); bufptr[tem] = 0; /* Trigger exit from the loop, but make sure we return to the caller a value which will indicate -- 2.39.2