Course outline

C / Advanced: Language Boundaries and Systems / Lesson 21

Bounded integer parsing at input boundaries

Validate C strtol conversion, complete records, and domain limits.

About 18 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Interpret strtol status and end pointers.
  • Check complete records and application bounds.
  • Interpret strtol value, end pointer, errno, and domain limits as separate evidence.
  • Design bounded input and unchanged-on-failure output policies.

Define the parsing contract

Converting text into an integer is a boundary between external bytes and an internal value. A robust contract specifies accepted syntax, range, whitespace, and what happens when extra characters remain. Conversion success alone does not establish that the value fits the application domain. Keep the original input available for a controlled diagnostic and avoid reporting sensitive contents unnecessarily.

Inspect conversion status

strtol returns a long and sets an end pointer to the first character it did not consume. Set errno to zero immediately before conversion, then check whether any digits were consumed and whether ERANGE indicates overflow or underflow. The example uses fixed input and checks its full consumption. A returned zero alone cannot distinguish valid zero from a failed conversion.

c Checked numeric parsing
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    const char *text = "42";
    char *end;
    errno = 0;
    long value = strtol(text, &end, 10);
    if (text == end || errno == ERANGE || *end != '\0') return 1;
    printf("%ld\n", value);
    return 0;
}
Expected output
42

The end pointer and errno distinguish complete valid input from conversion failure.

Check the domain range

Even a value representable as long may not fit the narrower type or range needed by the program. Check the domain limits before casting or assigning. The second example accepts an integer from zero through one hundred only after confirming conversion and complete consumption. A different application may permit signs or whitespace; state and test that policy rather than assuming the parser enforces it automatically.

c Checked numeric parsing
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    const char *text = "101";
    char *end;
    errno = 0;
    long value = strtol(text, &end, 10);
    if (text == end || errno == ERANGE || *end != '\0' || value < 0 || value > 100) {
        puts("rejected");
        return 0;
    }
    printf("%ld\n", value);
    return 0;
}
Expected output
rejected

The value parses but lies outside the application range.

Respect record boundaries

A line-reading function must also report whether it obtained a complete record. A buffer filled before the delimiter may contain only a prefix, and parsing that prefix as a complete number could accept unintended input. Choose a bounded strategy for rejecting or consuming the remainder. Embedded null bytes need an explicit policy when the input source can contain arbitrary bytes, because C string functions stop at the first null.

Test the boundary table

Build a table containing zero, a normal value, both domain endpoints, an out-of-range value, no digits, trailing characters, and a value beyond long range. Assert that rejected input does not reach the operation that consumes the result. Run tests on the intended implementations because type limits vary. A diagnostic tool can supplement these cases, but cannot replace an explicit parsing contract.

Define the parser boundary

A bounded integer parser should state its input representation, accepted syntax, numeric range, output type, and failure behavior. A null-terminated string contract differs from a pointer-and-length contract: strtol needs a terminating null within accessible storage, so a byte span from a system read cannot be passed to it as a string without first establishing a safe terminator. Limit input length before copying, reserve space for the terminator, and decide whether leading whitespace, signs, and trailing whitespace are allowed.

Separate syntax from domain rules. For a decimal quantity in the inclusive range zero through one hundred, "101" can convert to long successfully but must still be rejected by the application. A caller should not receive a partially converted value on failure unless the contract explicitly permits it. Initialize an output sentinel and test that it remains unchanged when the parser promises unchanged-on-failure behavior.

Interpret strtol evidence in order

Set errno to zero immediately before strtol when checking ERANGE. After the call, end == text means no digits were converted; a returned numeric zero alone is not enough because "0" is a valid conversion. If digits were converted, inspect the remaining input through end. Under a complete-record policy, *end must be the terminating null after any deliberately permitted newline handling. Then reject ERANGE and values outside the application and destination ranges before casting.

strtol accepts leading whitespace and an optional sign according to its rules. If the application disallows either, check that policy explicitly rather than assuming the conversion function enforces it. A string such as "42x" has a converted prefix and an unconsumed suffix, while "101" has complete decimal syntax but may violate a domain maximum. Distinct diagnostic categories help identify which stage failed without echoing private input.

Protect lengths and arithmetic

For a bounded input span, validate its length and copy only accessible bytes into a destination with room for a null terminator before using string functions. Check length + 1 for overflow or compare against capacity in a way that avoids the addition. A fixed-size line reader must detect whether a newline fit or whether more input remains; an EOF-terminated final record is not automatically a read failure. Never parse stale buffer contents after a failed read.

When converting a long result to int, compare it with INT_MIN and INT_MAX before the cast if the destination contract requires int. Do not perform an overflowing signed operation to test whether it overflows. For a digit-by-digit parser, check the accumulator before multiplying by ten and adding a digit, and define a sign policy. The examples use strtol and fixed synthetic strings so the end-pointer and range checks remain visible.

Preserve output and diagnostics

A parser interface can return a status and write through an output pointer only on success. Check that the pointer is valid according to the contract before dereferencing it, and leave the caller’s prior value unchanged when failure promises that behavior. Test invalid syntax, suffix, conversion range, and domain range independently. A status-only test can miss an accidental write before the failure is reported.

A diagnostic should identify a safe category or record number, not automatically include the entire untrusted input. If the parser is part of a larger stream, decide what happens to an overlong remainder and to records already processed before a later failure. The parser’s successful numeric conversion is not authorization to perform a downstream effect. Keep that decision at its own boundary.

Test complete and rejected records

Use fixed synthetic fixtures for empty input, valid zero, signed input if permitted, a valid upper bound, a numeric prefix with a suffix, a value just beyond the domain, and conversion overflow. Verify the end pointer, errno when relevant, status, and output sentinel. A very large decimal fixture can exceed the local long range, but its exact required length is implementation-dependent; label such a result as local evidence rather than a universal width claim.

The complete programs below use null-terminated fixed strings, checked small buffers, and C17 standard-library functions. They were compiled and run locally with warnings enabled in a temporary directory. The overflow example is qualified to the local implementation, while the other fixed values fit the required standard ranges. No program reads beyond a buffer or performs signed overflow to demonstrate a result.

20 worked examples

1. Accept a valid zero

Problem: Convert a complete zero record and check that digits were consumed.

  1. strtol returns the numeric value zero after consuming the digit.
  2. The end pointer advances to the terminator, so the syntax check succeeds.
c Accept a valid zero
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

int main(void) {
    char *end; const char *text = "0"; long value = strtol(text, &end, 10); printf("%ld %d\n", value, end != text && *end == '\0');
    return 0;
}
Expected output
0 1

Why this result follows: A zero numeric result can represent a successful conversion.

2. Detect an empty record

Problem: Check an empty string for conversion without relying on its numeric result.

  1. No digits are available for strtol to convert.
  2. The return is zero and end remains equal to text.
c Detect an empty record
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

int main(void) {
    char *end; const char *text = ""; long value = strtol(text, &end, 10); printf("%ld %d\n", value, end == text);
    return 0;
}
Expected output
0 1

Why this result follows: The end pointer distinguishes no conversion from valid numeric zero.

3. Detect a nondigit start

Problem: Identify a fixed record that begins with no convertible decimal digits.

  1. The first character x cannot start the requested decimal number.
  2. The end pointer remains at the original text.
c Detect a nondigit start
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

int main(void) {
    char *end; const char *text = "x"; (void)strtol(text, &end, 10); printf("%d\n", end == text);
    return 0;
}
Expected output
1

Why this result follows: Comparing end with text detects that no conversion occurred.

4. Accept a complete decimal

Problem: Convert a fixed decimal record and inspect its terminator.

  1. The digits convert to long value forty-two.
  2. The end pointer reaches the null terminator after the digits.
c Accept a complete decimal
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

int main(void) {
    char *end; long value = strtol("42", &end, 10); printf("%ld %d\n", value, *end == '\0');
    return 0;
}
Expected output
42 1

Why this result follows: Full consumption can be checked separately from the numeric value.

5. Reject an unconsumed suffix

Problem: Inspect the unconverted character after a valid numeric prefix.

  1. The initial digits convert to forty-two.
  2. The end pointer stops at x rather than the terminator.
c Reject an unconsumed suffix
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

int main(void) {
    char *end; long value = strtol("42x", &end, 10); printf("%ld %c\n", value, *end);
    return 0;
}
Expected output
42 x

Why this result follows: A complete-record contract can reject the remaining suffix.

6. Reject a domain excess

Problem: Check complete decimal syntax and a maximum of one hundred.

  1. The digits are consumed completely, so the syntax test succeeds.
  2. The value one hundred one exceeds the domain maximum.
c Reject a domain excess
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

int main(void) {
    char *end; long value = strtol("101", &end, 10); printf("%d %d\n", *end == '\0', value <= 100);
    return 0;
}
Expected output
1 0

Why this result follows: Successful conversion does not imply acceptance by the application range.

7. Accept an upper boundary

Problem: Check the inclusive maximum of a synthetic zero-to-one-hundred domain.

  1. The input converts fully to one hundred.
  2. The value is equal to the maximum, so the inclusive check succeeds.
c Accept an upper boundary
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

int main(void) {
    char *end; long value = strtol("100", &end, 10); printf("%d %d\n", *end == '\0', value <= 100);
    return 0;
}
Expected output
1 1

Why this result follows: A boundary test verifies that equality is accepted by the stated rule.

8. Reject a negative domain value

Problem: Separate signed decimal syntax from a nonnegative application rule.

  1. strtol accepts the sign and consumes negative one completely.
  2. The nonnegative range test fails.
c Reject a negative domain value
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

int main(void) {
    char *end; long value = strtol("-1", &end, 10); printf("%d %d\n", *end == '\0', value >= 0);
    return 0;
}
Expected output
1 0

Why this result follows: The parser and the application domain enforce different conditions.

9. Observe an explicit plus sign

Problem: Convert a fixed signed decimal record under strtol syntax.

  1. The plus sign is accepted before the digit seven.
  2. The end pointer reaches the terminator and the value is seven.
c Observe an explicit plus sign
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

int main(void) {
    char *end; long value = strtol("+7", &end, 10); printf("%ld %d\n", value, *end == '\0');
    return 0;
}
Expected output
7 1

Why this result follows: An application that forbids the sign needs a separate policy check.

10. Observe leading whitespace

Problem: Convert fixed text containing a leading space.

  1. strtol skips the leading whitespace and converts seven.
  2. The end pointer reaches the terminator.
c Observe leading whitespace
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

int main(void) {
    char *end; long value = strtol(" 7", &end, 10); printf("%ld %d\n", value, *end == '\0');
    return 0;
}
Expected output
7 1

Why this result follows: A stricter whitespace policy must be implemented explicitly.

11. Observe trailing whitespace

Problem: Inspect the suffix left after a number followed by a space.

  1. The initial digit converts to seven.
  2. The end pointer points at the trailing space.
c Observe trailing whitespace
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

int main(void) {
    char *end; long value = strtol("7 ", &end, 10); printf("%ld %d\n", value, *end == ' ' );
    return 0;
}
Expected output
7 1

Why this result follows: A complete-record rule must decide whether that remaining space is allowed.

12. Detect local long overflow

Problem: Check a very large synthetic decimal string against the local long range.

  1. The fixed magnitude exceeds the local implementation’s long range.
  2. strtol sets errno to ERANGE in this qualified run.
c Detect local long overflow
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

int main(void) {
    errno = 0; char *end; (void)strtol("999999999999999999999999999999999999999999", &end, 10); printf("%d\n", errno == ERANGE);
    return 0;
}
Expected output
1

Why this result follows: Resetting errno before the call makes the range signal attributable to this conversion.

13. Observe a small in-range conversion

Problem: Convert a small decimal after clearing errno and inspect the range signal.

  1. Twenty-five is representable as long.
  2. The conversion returns 25 without setting ERANGE in this fixture.
c Observe a small in-range conversion
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

int main(void) {
    errno = 0; char *end; long value = strtol("25", &end, 10); printf("%ld %d\n", value, errno == ERANGE);
    return 0;
}
Expected output
25 0

Why this result follows: A valid small value is distinguished from a conversion range failure.

14. Check before narrowing

Problem: Convert a known long value to int only after checking its destination range.

  1. Fifty lies between INT_MIN and INT_MAX.
  2. The cast yields int value fifty.
c Check before narrowing
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

int main(void) {
    long value = 50; if (value >= INT_MIN && value <= INT_MAX) { int result = (int)value; printf("%d\n", result); }
    return 0;
}
Expected output
50

Why this result follows: The range check precedes the narrowing conversion.

15. Remove a captured newline

Problem: Normalize a writable fixed line before complete-record conversion.

  1. strcspn locates the captured newline and replaces it with a null.
  2. strtol then consumes the resulting string 42 completely.
c Remove a captured newline
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

int main(void) {
    char line[] = "42\n"; line[strcspn(line, "\n")] = '\0'; char *end; long value = strtol(line, &end, 10); printf("%ld %d\n", value, *end == '\0');
    return 0;
}
Expected output
42 1

Why this result follows: The newline policy is applied before checking the remaining suffix.

16. Copy a bounded record

Problem: Copy a two-character synthetic record with room for its terminator.

  1. The source length two is less than capacity three.
  2. The copy includes the null and prints 42.
c Copy a bounded record
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

int main(void) {
    const char src[] = "42"; char dst[3]; size_t len = strlen(src); if (len < sizeof dst) { memcpy(dst, src, len + 1); puts(dst); }
    return 0;
}
Expected output
42

Why this result follows: The strict capacity check reserves a position for termination.

17. Reject an overlong copy

Problem: Reject a three-character source for a three-character destination.

  1. The source length equals capacity, leaving no position for its null.
  2. The copy is skipped and the destination remains ok.
c Reject an overlong copy
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

int main(void) {
    const char src[] = "123"; char dst[3] = "ok"; size_t len = strlen(src); if (len >= sizeof dst) puts(dst);
    return 0;
}
Expected output
ok

Why this result follows: A complete string copy requires length less than capacity.

18. Preserve output on domain failure

Problem: Reject a synthetic out-of-range value while retaining an output sentinel.

  1. The value 101 fails the maximum of 100.
  2. The conditional write is skipped and out remains ninety-nine.
c Preserve output on domain failure
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

int main(void) {
    int out = 99; long value = 101; int ok = value >= 0 && value <= 100; if (ok) out = (int)value; printf("%d %d\n", ok, out);
    return 0;
}
Expected output
0 99

Why this result follows: Validation before assignment supports an unchanged-on-failure contract.

19. Write a valid result

Problem: Accept a fixed in-range quantity and update the output.

  1. Twenty-five lies within zero through one hundred.
  2. The validated cast writes 25 and the status is true.
c Write a valid result
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

int main(void) {
    int out = 99; long value = 25; int ok = value >= 0 && value <= 100; if (ok) out = (int)value; printf("%d %d\n", ok, out);
    return 0;
}
Expected output
1 25

Why this result follows: A success case verifies the parser does not merely reject every input.

20. Inspect the final position

Problem: Check the terminator reached after parsing a short fixed record.

  1. The conversion consumes both decimal digits.
  2. The next character is the terminating null.
c Inspect the final position
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

int main(void) {
    char *end; long value = strtol("12", &end, 10); printf("%ld %d\n", value, end[0] == '\0');
    return 0;
}
Expected output
12 1

Why this result follows: The end pointer identifies where conversion stopped within the input string.

Common errors and fixes

Malformed text becomes zero

Why it happens
The return value was checked without the end pointer.
How to fix it
Reject when no digits were consumed.
Prevent it next time
Test valid zero and invalid text separately.

An overflowing number is accepted

Why it happens
ERANGE was not checked after conversion.
How to fix it
Reset errno before conversion and inspect it afterward.
Prevent it next time
Test a value outside long range.

A number with trailing text is accepted

Why it happens
The program did not inspect the remaining characters.
How to fix it
Enforce the specified trailing-character policy.
Prevent it next time
Include trailing characters in boundary tests.

20 practice exercises

1. Why is a returned zero insufficient to establish conversion success?

Show hint

Compare the end pointer with the original input and inspect the remainder.

Show worked solution

Both valid zero and a conversion with no digits can return zero. Check whether the end pointer advanced and inspect the remaining input.

Both a valid "0" and an input with no converted digits can return numeric zero. Check whether end advanced and then inspect the remaining input; do not classify conversion from the numeric value alone.

Check your solution

  • Valid zero advances end to the terminator
  • No-digit input leaves end equal to the original pointer

2. What should happen when 101 parses but the allowed range is zero through 100?

Show hint

Apply the application maximum after complete numeric conversion.

Show worked solution

Reject the value at the domain boundary even though conversion to long succeeded. The later consumer should not receive it.

The text 101 can parse completely to long, but it exceeds the inclusive maximum 100. Reject it at the domain boundary and do not pass it to the later consumer as a valid quantity.

Check your solution

  • Decimal conversion can succeed
  • The domain rejects 101 before downstream use

3. Predict the value and remaining suffix for strtol(" -12kg", &end, 10), assuming long can represent -12.

Show hint

Trace leading whitespace, the sign, and the first nonnumeric character.

Show worked solution

strtol skips the leading space, converts -12, and leaves end pointing to k. A complete-record decimal policy rejects the remaining "kg" suffix even though the numeric prefix converted successfully.

Check your solution

  • The converted long value is -12
  • The remaining suffix begins with k

4. Repair a parser that checks errno == ERANGE after strtol but never clears errno first.

Show hint

Reset errno immediately before the conversion and inspect the end pointer too.

Show worked solution

Set errno = 0 immediately before calling strtol, then check ERANGE after the call. For the fixed text "17", also require end to advance and reach the terminator. This prevents a stale range error from a prior operation being mistaken for failure of the current conversion.

Check your solution

  • errno is cleared immediately before strtol
  • For "17", conversion consumes both digits and reaches the terminator

5. A two-byte span contains the characters 8 and 5, has no terminator, and must be parsed within 0 through 100. Describe the safe integration.

Show hint

Copy only the accessible span into a buffer that has room for a null.

Show worked solution

Copy the two bytes into a three-character buffer, write a null at index 2, and call strtol after clearing errno. Require digits, full consumption, no ERANGE, and the domain range before writing the output. The resulting validated quantity is 85; no byte beyond the original span is read.

Check your solution

  • The temporary buffer is terminated at index 2
  • The validated output is 85 and the original two-byte span is not overread

6. A parser accepts complete decimal values from 0 through 100. Classify "101".

Show hint

Check syntax and domain range separately.

Show worked solution

The text converts completely to 101, so its decimal syntax is valid. It exceeds the maximum 100 and must be rejected at the domain boundary before a downstream consumer receives it.

Check your solution

  • The syntax is complete
  • The domain range rejects 101

7. Under the same inclusive 0 through 100 contract, classify "100" and "0".

Show hint

Both endpoints are included.

Show worked solution

Both strings convert fully and lie at accepted endpoints. A test should assert successful status and outputs 100 and 0, proving that valid zero is not confused with conversion failure.

Check your solution

  • Both endpoints are accepted
  • The output values are 100 and 0

8. Explain why errno is cleared before checking whether strtol reports ERANGE.

Show hint

A previous operation could leave errno nonzero.

Show worked solution

Set errno = 0 immediately before conversion and inspect errno == ERANGE afterward. This avoids mistaking a stale value for the current conversion’s range failure; also check the end pointer.

Check your solution

  • errno is cleared before the call
  • ERANGE and end are checked afterward

9. A long result must be stored as int. What check precedes the cast?

Show hint

Compare against the destination type’s limits.

Show worked solution

Require INT_MIN <= value && value <= INT_MAX before converting to int. The text conversion and application domain must also have succeeded. Reject out-of-range values without writing the output.

Check your solution

  • The value lies within int limits
  • The cast and output write follow validation

10. A parser’s output starts at 99 and input "101" violates its maximum 100. What should a failure-safe contract require?

Show hint

Validate before writing through the output pointer.

Show worked solution

Return failure and leave the output exactly 99 if unchanged-on-failure is promised. Test both the status and sentinel because a premature write could otherwise escape a status-only test.

Check your solution

  • The status reports failure
  • The output remains 99

11. strtol accepts leading whitespace. How can a stricter parser reject " 7"?

Show hint

Apply the application policy before or alongside conversion.

Show worked solution

Check the first character or otherwise validate the permitted syntax explicitly, then reject the leading space. Do not assume strtol itself enforces a no-whitespace policy. Test a permitted value such as "7" separately.

Check your solution

  • The leading-space record is rejected
  • The ordinary record 7 is accepted

12. strtol accepts a leading plus sign. What decision must a parser make for "+7"?

Show hint

The application contract can be stricter than strtol.

Show worked solution

Document whether a plus sign is allowed. If forbidden, reject "+7" explicitly; if allowed, verify full conversion and range. Successful strtol conversion alone does not choose the application’s sign policy.

Check your solution

  • The sign policy is explicit
  • The chosen policy is tested

13. For a pointer-and-length span of two bytes containing 42, why not pass it directly to strtol?

Show hint

strtol expects an accessible null-terminated string.

Show worked solution

The span may not contain a null terminator within accessible storage. Copy the validated two bytes into a buffer with room for a terminator, add it, then parse under the documented length policy.

Check your solution

  • An accessible terminator is established
  • No byte beyond the span is read

14. A destination buffer has capacity 3 and source text "42". Does the complete string fit?

Show hint

Reserve a position for the null terminator.

Show worked solution

The source length is 2 and 2 < 3, so copying three bytes including the terminator fits exactly. Check capacity before copying and preserve the destination on rejection if the contract promises it.

Check your solution

  • The length is 2
  • Three bytes including null fit

15. A destination buffer has capacity 3 and source text "123". Why reject a complete copy?

Show hint

The terminating null needs one more position.

Show worked solution

The source length equals capacity, so a complete copy needs four bytes and cannot fit. Reject it before writing under an unchanged-on-failure contract; truncation would require a separate policy.

Check your solution

  • The complete copy is rejected
  • The destination is not partially changed

16. A captured line is "42 " in a writable array. How can the newline be handled before parsing?

Show hint

Replace the captured newline under a documented line policy.

Show worked solution

After a successful bounded read, locate the newline within the terminated array and replace it with a null. Parse the resulting "42" and require complete consumption. Distinguish this from a line whose newline did not fit.

Check your solution

  • The resulting record is 42
  • The parser checks complete consumption

17. An eight-character buffer captures seven letters but not the following newline. Why not parse the prefix automatically?

Show hint

The record may continue beyond the captured buffer.

Show worked solution

The seven letters fill the available input positions and the newline remains unread. Apply the documented overlong-record or completion policy, including draining the remainder when required, rather than accepting an ambiguous prefix.

Check your solution

  • The newline remains unread
  • The prefix is not silently accepted

18. An empty stream makes fgets return NULL while the buffer contains old data. What should the parser do?

Show hint

Check the read result before examining the buffer.

Show worked solution

Report end-of-input or the appropriate read error and do not parse the old contents as a new record. Inspect feof and ferror if the application needs to distinguish those conditions.

Check your solution

  • No stale record is parsed
  • The input condition is reported

19. A very large decimal string sets ERANGE locally. What may be concluded about another implementation?

Show hint

long range can differ across implementations.

Show worked solution

The local result shows that the fixture exceeds that implementation’s long range. Another implementation may have a different range, so do not infer a universal width from this one observation.

Check your solution

  • The local ERANGE is reported accurately
  • No universal long width is claimed

20. Design a compact test set for a decimal parser accepting complete values from 0 through 100.

Show hint

Cover syntax, range, and failure-state boundaries.

Show worked solution

Test empty text, "0", "100", "101", a suffix such as "42x", and conversion overflow. Assert status and output sentinel on each failure, and verify accepted values separately.

Check your solution

  • Valid endpoints 0 and 100 succeed
  • Syntax, range, and output-preservation failures are checked

Key takeaways

  • Conversion, full consumption, and domain validation are separate checks.
  • Test limits and malformed records explicitly.
  • A returned zero does not distinguish valid zero from no converted digits.
  • A fully parsed value can still violate the application range.
  • A byte span needs an accessible terminator before use with strtol.

Official references