All lessons Leer en español

Security in depth · Unit 21 · Lesson 1 of 6

A length must fit the destination

Check a text conversion against a byte budget, including its terminator.

4 minreadyShort lesson

Helpful before thisMemory safety: boundaries and lifetimes

See all lessons in this topic

After this lesson you can

  • Calculate the required bytes from a supplied encoding record and identify the remaining validation step.

One idea. One situation. One reasoned decision.

How it works

Memory operations depend on sizes, offsets, and the lifetime of the destination. Validate the relationship between those values before copying or indexing, using safe abstractions where practical. Checking one input length is not enough if later arithmetic or encoding changes the required space. A crash can indicate a correctness problem without, by itself, proving any particular security consequence.

Input representation → Required capacity → Bounded operationInput representationRequired capacityBounded operation
Follow the relationship: Input representation → Required capacity → Bounded operation.

Count what the operation actually stores

A fictional name field passes through a native text adapter. Its contract requires UTF-8 bytes followed by one zero byte. The supplied encoding report already counts the actual bytes; you do not need to guess from the displayed text.

Record Encoding report Destination
A Four code points, four bytes Six bytes
B Four code points, seven bytes Six bytes

Worked decision: A needs five bytes including the terminator, so it fits this capacity check. B needs eight, leaving a two-byte shortfall. Both display four code points, yet they have different storage requirements. A code point is a Unicode value; it is not a promise of one byte or one visible symbol.

Do not silently cut B to six bytes. That could split an encoded sequence or omit the required terminator. Use the adapter’s documented conversion result and failure behavior. An eight-byte destination removes B’s stated capacity shortfall, but the implementation still needs valid input, checked arithmetic, and a live writable destination. Passing this calculation establishes only the stated size relationship.

The key distinction: Storage requirements depend on the actual encoding and operation.

Check yourself

No timer. No penalties. Read the explanation and try again whenever you like.

  1. Which conclusion follows from record B and this adapter contract?

    Show the answer

    Correct answer: Eight bytes are required; the current destination is two bytes short. Seven encoded bytes plus one required terminator need eight bytes. The six-byte destination fails this capacity check.

Try it

  • WriteWrite the required capacity and the shortfall for record B. Then change the destination to eight bytes and explain what else must be checked before accepting the conversion.
References