This is the mail archive of the
libc-alpha@sourceware.org
mailing list for the glibc project.
[PATCH] manual: Various fixes to the mbstouwcs example
- From: fweimer at redhat dot com (Florian Weimer)
- To: libc-alpha at sourceware dot org
- Date: Wed, 04 Apr 2018 15:57:40 +0200
- Subject: [PATCH] manual: Various fixes to the mbstouwcs example
The example did not work because the NUL byte was not converted, and
mbrtowc was called with a zero-length input string. This results in a
(size_t) -2 return value, so the function always returns NULL.
The size computation for the heap allocation of the result was
incorrect because it did not deal with integer overflow.
Error checking was missing, and the allocated memory was not freed on
error paths. All error returns now set errno. (Note that there is an
assumption that free does not clobber errno.)
The slightly unportable comparision against (size_t) -2 to catch both
(size_t) -1 and (size_t) -2 return values is gone as well.
2018-04-04 Florian Weimer <fweimer@redhat.com>
* manual/examples/mbstouwcs.c (mbstouwcs): Fix loop termination,
integer overflow, memory leak on error, and indeterminate errno
value.
* manual/charset.texi (Converting a Character): Adjust.
diff --git a/manual/charset.texi b/manual/charset.texi
index b37fac4df1..270995f602 100644
--- a/manual/charset.texi
+++ b/manual/charset.texi
@@ -681,9 +681,7 @@ is declared in @file{wchar.h}.
Use of @code{mbrtowc} is straightforward. A function that copies a
multibyte string into a wide character string while at the same time
-converting all lowercase characters into uppercase could look like this
-(this is not the final version, just an example; it has no error
-checking, and sometimes leaks memory):
+converting all lowercase characters into uppercase could look like this:
@smallexample
@include mbstouwcs.c.texi
diff --git a/manual/examples/mbstouwcs.c b/manual/examples/mbstouwcs.c
index 3a8b9a65f9..4012606bf1 100644
--- a/manual/examples/mbstouwcs.c
+++ b/manual/examples/mbstouwcs.c
@@ -7,8 +7,11 @@
wchar_t *
mbstouwcs (const char *s)
{
- size_t len = strlen (s);
- wchar_t *result = malloc ((len + 1) * sizeof (wchar_t));
+ /* Include the NUL terminator in the conversion. */
+ size_t len = strlen (s) + 1;
+ wchar_t *result = reallocarray (NULL, len + 1, sizeof (wchar_t));
+ if (result == NULL)
+ return NULL;
wchar_t *wcp = result;
wchar_t tmp[1];
mbstate_t state;
@@ -17,9 +20,19 @@ mbstouwcs (const char *s)
memset (&state, '\0', sizeof (state));
while ((nbytes = mbrtowc (tmp, s, len, &state)) > 0)
{
- if (nbytes >= (size_t) -2)
- /* Invalid input string. */
- return NULL;
+ if (nbytes == (size_t) -2)
+ {
+ /* Truncated input string. */
+ errno = EILSEQ;
+ free (result);
+ return NULL;
+ }
+ if (nbytes >= (size_t) -1)
+ {
+ /* Some other error (including EILSEQ). */
+ free (result);
+ return NULL;
+ }
*wcp++ = towupper (*tmp);
len -= nbytes;
s += nbytes;