Don't use memchr() on strings potentially shorter than 4 bytes.

When running profanity under Valgrind with slashguard enabled, the
following error could occur:

```
[...]
==4021347== Invalid read of size 1
==4021347==    at 0x4851F49: memchr (vg_replace_strmem.c:986)
==4021347==    by 0x45CEAD: _inp_slashguard_check (inputwin.c:183)
==4021347==    by 0x45CEAD: inp_readline (inputwin.c:225)
==4021347==    by 0x431184: prof_run (profanity.c:121)
==4021347==    by 0x42C609: main (main.c:176)
==4021347==  Address 0xe850883 is 0 bytes after a block of size 3 alloc'd
==4021347==    at 0x48477C4: malloc (vg_replace_malloc.c:446)
[...]
```

`memchr()` requires the complete memory that shall be searched to be
accessible. Using `strchr()` could work for shorter strings, but we only
want to search in the first 4 chars.

Instead of somehow working around those limitations, simply search manually
in the first 4 bytes.

Fixes: 3c56b289 ("Add slashguard feature")
Signed-off-by: Steffen Jaeckel <s@jaeckel.eu>
This commit is contained in:
Steffen Jaeckel
2025-08-20 16:09:13 +02:00
parent 65f5883fee
commit 7f48452d84

View File

@@ -180,11 +180,15 @@ _inp_slashguard_check(void)
return false;
if (!prefs_get_boolean(PREF_SLASH_GUARD))
return false;
if (memchr(inp_line + 1, '/', 3)) {
cons_show("Your text contains a slash in the first 4 characters");
free(inp_line);
inp_line = NULL;
return true;
size_t n = 1;
while (inp_line[n] != '\0' && n < 4) {
if (inp_line[n] == '/') {
cons_show("Your text contains a slash in the first 4 characters");
free(inp_line);
inp_line = NULL;
return true;
}
n++;
}
return false;
}