mtd-utils: common.h: fix prompt function

Message ID
State Accepted
Delegated to: David Oberhollenzer
Headers show
  • mtd-utils: common.h: fix prompt function
Related show

Commit Message

David Oberhollenzer Sept. 19, 2018, 9:18 a.m.
The prompt() function is intended to query a yes/no reply from a command
line user by reading in an entire line of text using getline() and checking
the first character. If the line is empty, a default value is returned.

First of all, this patch replaces the usage of getline() with fgets() to
avoid compilation problems on some smaller C libraries, like klibc, that
do not have a getline() implementation. Since we now have a static line
length, this may however break some build setups that input lengthy
giberish instead of a simple 'y' or 'n'.

Second, this patch fixes a more severe bug in prompt(), replacing a 'while'
keyword with the 'if' that was most likely intended. In the old version, if
getline() reported an error, it would print an error message inside a while
loop, immediately followed by a break and then march on and process the
erroneous input instead of using the default value as printed to stdout.

Signed-off-by: David Oberhollenzer <>
 include/common.h | 7 ++-----
 1 file changed, 2 insertions(+), 5 deletions(-)


David Oberhollenzer Oct. 2, 2018, 12:06 p.m. | #1
Applied to mtd-utils.git master.



diff --git a/include/common.h b/include/common.h
index 2ce5d22..ece2287 100644
--- a/include/common.h
+++ b/include/common.h
@@ -141,15 +141,14 @@  extern "C" {
 static inline bool prompt(const char *msg, bool def)
-	char *line = NULL;
-	size_t len;
 	bool ret = def;
+	char line[64];
 	do {
 		normsg_cont("%s (%c/%c) ", msg, def ? 'Y' : 'y', def ? 'n' : 'N');
-		while (getline(&line, &len, stdin) == -1) {
+		if (fgets(line, sizeof(line), stdin) == NULL) {
 			printf("failed to read prompt; assuming '%s'\n",
 				def ? "yes" : "no");
@@ -169,8 +168,6 @@  static inline bool prompt(const char *msg, bool def)
 	} while (1);
-	free(line);
 	return ret;