From cfd2e5142ad2d9650fb8d6348966127b873c0ae3 Mon Sep 17 00:00:00 2001 From: John Schneiderman Date: Sun, 29 Sep 2024 11:44:35 +0200 Subject: [PATCH 1/3] Changes from being mostly assembly to be based upon a C version. Adds the additional error conditions for get_s: truncation and too small buffer. --- include/stdio.c | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/include/stdio.c b/include/stdio.c index 4197ef5..0c7ec1d 100644 --- a/include/stdio.c +++ b/include/stdio.c @@ -1,6 +1,7 @@ #include "stdio.h" #include "conio.h" #include "stdlib.h" +#include "stdbool.h" void putchar(char c) { @@ -29,13 +30,29 @@ char * gets(char * str) char * gets_s(char * str, size_t n) { + if (str == NULL) + return NULL; + + if (n == 0 || n == 1) + return NULL; + str[0] = '\0'; char i = 0, t = n - 1; + bool isTruncated = false; + while ((char ch = getpch()) != '\n') { if (i < t) str[i++] = ch; + else + { + isTruncated = true; + break; + } } str[i] = 0; + + if (isTruncated) + return NULL; return str; } From ebce50320fa6a6abfebb7726c7fcba3cdd59c951 Mon Sep 17 00:00:00 2001 From: John Schneiderman Date: Mon, 30 Sep 2024 20:04:33 +0200 Subject: [PATCH 2/3] Fixes incorrect specification implementation not reading all the characters. Simplfies the buffer size checks. --- include/stdio.c | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/include/stdio.c b/include/stdio.c index 0c7ec1d..f24dcf1 100644 --- a/include/stdio.c +++ b/include/stdio.c @@ -33,25 +33,19 @@ char * gets_s(char * str, size_t n) if (str == NULL) return NULL; - if (n == 0 || n == 1) + if (n < 2) return NULL; - str[0] = '\0'; char i = 0, t = n - 1; - bool isTruncated = false; while ((char ch = getpch()) != '\n') { if (i < t) - str[i++] = ch; - else - { - isTruncated = true; - break; - } + str[i] = ch; + ++i; } - str[i] = 0; + str[(i < t) ? i : t] = '\0'; - if (isTruncated) + if (i > t) return NULL; return str; } From 534ddc3a4cb67f01293572c825e5de650b1a5fe7 Mon Sep 17 00:00:00 2001 From: John Schneiderman Date: Mon, 30 Sep 2024 20:07:44 +0200 Subject: [PATCH 3/3] Removes the include for STD bool since it's no longer used. --- include/stdio.c | 1 - 1 file changed, 1 deletion(-) diff --git a/include/stdio.c b/include/stdio.c index f24dcf1..634e939 100644 --- a/include/stdio.c +++ b/include/stdio.c @@ -1,7 +1,6 @@ #include "stdio.h" #include "conio.h" #include "stdlib.h" -#include "stdbool.h" void putchar(char c) {