Bird
Raised Fist0

Consider the following buggy UTF-8 validation code snippet. Which line contains the subtle bug that can cause invalid UTF-8 sequences to be accepted as valid?

medium🐞 Bug Identification Q14 of Q15
Bit Manipulation - UTF-8 Validation
Consider the following buggy UTF-8 validation code snippet. Which line contains the subtle bug that can cause invalid UTF-8 sequences to be accepted as valid?
def validUtf8(data):
    remaining = 0
    for byte in data:
        if remaining == 0:
            if (byte >> 5) == 0b110:
                remaining = 1
            elif (byte >> 4) == 0b1110:
                remaining = 2
            elif (byte >> 3) == 0b11110:
                remaining = 3
            elif (byte >> 7) == 0:
                remaining = 0
            else:
                return False
        else:
            # Bug: missing check for continuation byte pattern
            remaining -= 1
    return remaining == 0
ALine with 'if remaining == 0:' condition
BLine with 'remaining -= 1' inside else block
CLine with 'if (byte >> 5) == 0b110:' condition
DLine with 'return remaining == 0' at the end
Step-by-Step Solution
  1. Step 1: Identify where continuation bytes are checked

    The else block handles continuation bytes, which must start with bits '10' (binary 0b10).
  2. Step 2: Locate missing validation

    The code decrements remaining without checking if the byte starts with '10', allowing invalid bytes to pass.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Missing continuation byte pattern check causes acceptance of invalid sequences [OK]
Quick Trick: Check continuation bytes start with '10' before decrementing [OK]
Common Mistakes:
MISTAKES
  • Forgetting continuation byte pattern check
  • Miscounting remaining bytes
Trap Explanation:
PITFALL
  • Code looks correct but missing the critical check for continuation byte pattern leads to subtle bugs.
Interviewer Note:
CONTEXT
  • Tests candidate's ability to spot subtle bugs that pass many test cases but fail edge cases.
Master "UTF-8 Validation" in Bit Manipulation

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bit Manipulation Quizzes