Skip to content

reg: fix -Warray-bounds by casting to unsigned char before tolower() #98

@r1w1s1

Description

@r1w1s1

Using gcc (GCC) 15.2.0 on Slackware-current x86_64

Building with -Wall on GCC produces:

reg.c:50: warning: array subscript [-128, 255] is outside array bounds of 'char *[256]' [-Warray-bounds=]
reg.c:51: warning: array subscript [-128, 255] is outside array bounds of 'char *[256]' [-Warray-bounds=]

On platforms where char is signed (e.g. x86), tolower() called with a plain char can produce a negative value,
resulting in an out-of-bounds index into bufs[] and lnmode[]. Casting to unsigned char before tolower()
ensures the index stays within [0, 255].

This was previously raised in #55. Submitting as a focused patch addressing only the bounds issue in reg_putraw().

--- a/reg.c
+++ b/reg.c
@@ -43,13 +43,13 @@
 
 static void reg_putraw(int c, char *s, int ln)
 {
-	char *pre = isupper(c) && bufs[tolower(c)] ? bufs[tolower(c)] : "";
+	char *pre = isupper(c) && bufs[tolower((unsigned char)c)] ? bufs[tolower((unsigned char)c)] : "";
 	char *buf = malloc(strlen(pre) + strlen(s) + 1);
 	strcpy(buf, pre);
 	strcat(buf, s);
-	free(bufs[tolower(c)]);
-	bufs[tolower(c)] = buf;
-	lnmode[tolower(c)] = ln;
+	free(bufs[tolower((unsigned char)c)]);
+	bufs[tolower((unsigned char)c)] = buf;
+	lnmode[tolower((unsigned char)c)] = ln;
 }
 
 void reg_put(int c, char *s, int ln)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions