Project Info Name.......: gnu-hello
Description: GNU Hello


gnu-hello       
Info
Commit...:5ac771102c71b79c285266a16c07be7dec8f3713
Author...:Sami Kerola
Committer:Sami Kerola
Date.....:Sun Jan 20 21:26:54 2019 +0000
Parents..:1695c00b1aacc762208e1557acbf9e2a679071ee

Message
hello: use strlen() to find greeting length

* src/hello.c: ditto.
* tests/multibyte-1: check multibyte strings fail correctly.
* Makefile.am: make autotools aware of the new test.

Changes
diff --git a/Makefile.am b/Makefile.am
line changes: +1/-0
index 5576d24..1361dca
--- a/Makefile.am
+++ b/Makefile.am
@@ -64,6 +64,7 @@ TESTS = \
 	tests/greeting-2 \
 	tests/hello-1 \
 	tests/last-1 \
+	tests/multibyte-1 \
 	tests/traditional-1
 
 EXTRA_DIST += $(TESTS)

diff --git a/src/hello.c b/src/hello.c
line changes: +4/-3
index 9be4134..afd5dbf
--- a/src/hello.c
+++ b/src/hello.c
@@ -54,6 +54,7 @@ main (int argc, char *argv[])
   int lose = 0;
   const char *greeting_msg;
   wchar_t *mb_greeting;
+  mbstate_t mbstate = { 0, };
   size_t len;
 
   enum {
@@ -118,11 +119,11 @@ main (int argc, char *argv[])
       exit (EXIT_FAILURE);
     }
 
-  len = mbsrtowcs(NULL, &greeting_msg, 0, NULL);
+  len = strlen(greeting_msg) + 1;
+  mb_greeting = xmalloc(len * sizeof(wchar_t));
+  len = mbsrtowcs(mb_greeting, &greeting_msg, len, &mbstate);
   if (len == (size_t)-1)
     error (EXIT_FAILURE, errno, _("conversion to a multibyte string failed"));
-  mb_greeting = xmalloc((len + 1) * sizeof(wchar_t));
-  mbsrtowcs(mb_greeting, &greeting_msg, len + 1, NULL);
 
   /* Print greeting message and exit. */
   wprintf (L"%ls\n", mb_greeting);

diff --git a/tests/multibyte-1 b/tests/multibyte-1
line changes: +38/-0
index 0000000..f44cbe8
--- /dev/null
+++ b/tests/multibyte-1
@@ -0,0 +1,38 @@
+#! /bin/sh
+# Test multibyte --greeting.
+#
+# Copyright (C) 2019 Free Software Foundation, Inc.
+#
+# Copying and distribution of this file, with or without modification,
+# are permitted in any medium without royalty provided the copyright
+# notice and this notice are preserved.
+
+trap 'rm -fr $tmpfiles' 1 2 3 15
+
+# Cause multibyte conversion failure.
+LANGUAGE=
+LC_ALL=C
+LC_MESSAGES=
+LANG=
+export LANGUAGE LC_ALL LC_MESSAGES LANG
+
+tmpfiles="multibyte-test1.ok"
+cat <<EOF >multibyte-test1.ok
+hello: conversion to a multibyte string failed: Invalid or incomplete multibyte or wide character
+EOF
+
+tmpfiles="$tmpfiles multibyte-test1.out"
+: ${HELLO=hello}
+${HELLO} -g 'hello 世界' 2>&1 | tr -d '\r' >multibyte-test1.out
+
+# remove \r (CR) characters from the output, so that the tests work on
+# platforms with CRLF line endings.  There is apparently no reliable
+# method (across Cygwin, MingW, etc.) to force an eol style.
+
+: ${DIFF=diff}
+${DIFF} multibyte-test1.ok multibyte-test1.out
+result=$?
+
+rm -fr $tmpfiles
+
+exit $result

This website is licensed under AGPL-3.0. Feel free to copy!