Skip to content

Commit

Permalink
Relax our checks for memchr on C11 and above
Browse files Browse the repository at this point in the history
Since C11:

> This function behaves as if it reads the bytes sequentially and stops as soon
as a matching bytes is found: if the array pointed to by ptr is smaller than
count, but the match is found within the array, the behavior is well-defined.

Reported-by: q66
  • Loading branch information
jvoisin committed Mar 19, 2024
1 parent 140cffb commit 8ed72e7
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 1 deletion.
4 changes: 3 additions & 1 deletion include/string.h
Original file line number Diff line number Diff line change
Expand Up @@ -123,10 +123,12 @@ _FORTIFY_FN(memchr) void *memchr(const void * _FORTIFY_POS0 __d, int __c, size_t
if (!__d)
__builtin_trap();

#if __STDC_VERSION__ < 201112L
__fh_size_t __b = __fh_bos(__d, 0);

if (__n > __b)
__builtin_trap();
#endif

return __builtin_memchr(__d, __c, __n);
#endif
}
Expand Down
2 changes: 2 additions & 0 deletions tests/test_memchr_dynamic_read.c
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include <string.h>

int main(int argc, char** argv) {
#if __STDC_VERSION__ < 201112L
const char* buffer = "12345";
memchr(buffer, (int)'4', strlen(buffer) - 1);
puts(buffer);
Expand All @@ -12,5 +13,6 @@ int main(int argc, char** argv) {
CHK_FAIL_END

puts(buffer);
#endif
return ret;
}
2 changes: 2 additions & 0 deletions tests/test_memchr_static_read.c
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include <string.h>

int main(int argc, char** argv) {
#if __STDC_VERSION__ < 201112L
const char* buffer = "12345";
const char* padding = "ABCDEFGHIJKLMN";
memchr(buffer, (int)'4', strlen(buffer) - 1);
Expand All @@ -13,5 +14,6 @@ int main(int argc, char** argv) {
CHK_FAIL_END

puts(buffer);
#endif
return ret;
}

0 comments on commit 8ed72e7

Please sign in to comment.