Skip to content

Commit 2c3cac2

Browse files
Fix stale char_ptr for find_first_character_wide read
On exit from the loop, char_ptr had not been updated to match block_ptr, resulting in erroneous results. Moving all updates out of the loop fixes that.
1 parent 1e3a1ce commit 2c3cac2

File tree

2 files changed

+10
-5
lines changed

2 files changed

+10
-5
lines changed

libc/src/string/string_utils.h

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -136,11 +136,11 @@ find_first_character_wide_read(const unsigned char *src, unsigned char ch,
136136
const Word ch_mask = repeat_byte<Word>(ch);
137137

138138
// Step 2: read blocks
139-
for (const Word *block_ptr = reinterpret_cast<const Word *>(char_ptr);
140-
!has_zeroes<Word>((*block_ptr) ^ ch_mask) && cur < n;
141-
++block_ptr, cur += sizeof(Word)) {
142-
char_ptr = reinterpret_cast<const unsigned char *>(block_ptr);
143-
}
139+
const Word *block_ptr = reinterpret_cast<const Word *>(char_ptr);
140+
for (; !has_zeroes<Word>((*block_ptr) ^ ch_mask) && cur < n;
141+
++block_ptr, cur += sizeof(Word))
142+
;
143+
char_ptr = reinterpret_cast<const unsigned char *>(block_ptr);
144144

145145
// Step 3: find the match in the block
146146
for (; *char_ptr != ch && cur < n; ++char_ptr, ++cur) {

libc/test/src/string/memchr_test.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,11 @@ const char *call_memchr(const void *src, int c, size_t size) {
2121
return reinterpret_cast<const char *>(LIBC_NAMESPACE::memchr(src, c, size));
2222
}
2323

24+
TEST(LlvmLibcMemChrTest, FromProtoC) {
25+
const char *src = "protobuf_cpp_version$\n";
26+
ASSERT_STREQ(call_memchr(src, '$', 22), "$\n");
27+
}
28+
2429
TEST(LlvmLibcMemChrTest, FindsCharacterAfterNullTerminator) {
2530
// memchr should continue searching after a null terminator.
2631
const size_t size = 5;

0 commit comments

Comments
 (0)