From 74a080fb68df849e9f6230e9508cf9ec6dcb8a18 Mon Sep 17 00:00:00 2001 From: Liav A Date: Mon, 17 Oct 2022 20:34:21 +0300 Subject: [PATCH] LibC: Use proper casting in fgetc and fgetc_unlocked functions In the fgetc function, a fix was already in place but was clunky. A real proper solution is to use an unsigned char instead of a char when returning the value, so an implicit cast is happening based on the assumption that the value is unsigned, so if the variable contained 0xff it won't be treated as -1, but as unsigned 0xff, so the result int will be 0xff and not -1. The same solution is applied to the fgetc_unlocked function as well. --- Userland/Libraries/LibC/stdio.cpp | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/Userland/Libraries/LibC/stdio.cpp b/Userland/Libraries/LibC/stdio.cpp index a4d372e6d03..5c6247bc085 100644 --- a/Userland/Libraries/LibC/stdio.cpp +++ b/Userland/Libraries/LibC/stdio.cpp @@ -631,12 +631,10 @@ char* fgets(char* buffer, int size, FILE* stream) int fgetc(FILE* stream) { VERIFY(stream); - char ch; - size_t nread = fread(&ch, sizeof(char), 1, stream); + unsigned char ch; + size_t nread = fread(&ch, sizeof(unsigned char), 1, stream); if (nread == 1) { - // Note: We do this static_cast because otherwise when casting a char that contains - // 0xFF results in an int containing -1, so an explicit cast is required here. - return static_cast(ch & 0xff); + return ch; } return EOF; } @@ -644,8 +642,8 @@ int fgetc(FILE* stream) int fgetc_unlocked(FILE* stream) { VERIFY(stream); - char ch; - size_t nread = fread_unlocked(&ch, sizeof(char), 1, stream); + unsigned char ch; + size_t nread = fread_unlocked(&ch, sizeof(unsigned char), 1, stream); if (nread == 1) return ch; return EOF;