testing-debugging · beginner · ~15 min
Validate boundary conditions defensively and safely write to caller-supplied output pointers.
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.
Implement:
int validate_score(int score, int *category);
category == NULL, return -1 immediately.score < 0 or score > 100, return -1 and do not modify *category.score >= 90, set *category = 1 and return 0.score >= 75 (and < 90), set *category = 2 and return 0.score >= 50 (and < 75), set *category = 3 and return 0.score < 50 (and >= 0), set *category = 4 and return 0.int cat = 0;
validate_score(95, &cat); // returns 0, cat == 1
validate_score(105, &cat); // returns -1, cat remains 1
score: integer test score; category: pointer to integer output buffer.
Returns 0 on valid score; -1 on NULL pointer or out-of-range score.
Score must be in range [0, 100]. Category pointer must not be NULL.
#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;
}
Dereferencing category before NULL check; overwriting category on invalid score; using > instead of >= for grade thresholds.
score == 0 sets category 4; score == 100 sets category 1; negative score returns -1 without touching category; NULL category returns -1.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.