testing-debugging · beginner · ~15 min

Assert Input Range Validator

Validate boundary conditions defensively and safely write to caller-supplied output pointers.

Challenge

Defensive programming requires validating boundary conditions before executing business logic. In production systems, public API boundaries should return structured error codes rather than crashing, while enforcing strict domain ranges.

Your Task

Implement:

int validate_score(int score, int *category);

Rules

  1. If category == NULL, return -1 immediately.
  2. If score < 0 or score > 100, return -1 and do not modify *category.
  3. If score >= 90, set *category = 1 and return 0.
  4. If score >= 75 (and < 90), set *category = 2 and return 0.
  5. If score >= 50 (and < 75), set *category = 3 and return 0.
  6. If score < 50 (and >= 0), set *category = 4 and return 0.

Example

int cat = 0;
validate_score(95, &cat); // returns 0, cat == 1
validate_score(105, &cat); // returns -1, cat remains 1

Input format

score: integer test score; category: pointer to integer output buffer.

Output format

Returns 0 on valid score; -1 on NULL pointer or out-of-range score.

Constraints

Score must be in range [0, 100]. Category pointer must not be NULL.

Starter code

#include <stddef.h>

/* Validate score (0-100) and set category (1: >=90, 2: >=75, 3: >=50, 4: <50).
   Return 0 on success, or -1 if score is invalid or category is NULL. */
int validate_score(int score, int *category) {
    (void)score; (void)category;
    return -1;
}

Common mistakes

Dereferencing category before NULL check; overwriting category on invalid score; using > instead of >= for grade thresholds.

Edge cases to handle

score == 0 sets category 4; score == 100 sets category 1; negative score returns -1 without touching category; NULL category returns -1.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.