cybersecurity · intermediate · ~15 min · safe pentest lab
Safely tokenize delimited text inputs with strict bounds on token length and token count.
The standard C strtok() function is thread-unsafe and mutates its input in-place. Parsers processing untrusted inputs need a safe tokenizer that bounds token lengths and prevents array overflow.
Implement:
int safe_tokenize(const char *input, char delimiter, char tokens[][64], size_t max_tokens);
Split input by delimiter into fixed 64-byte slots in tokens.
input == NULL, tokens == NULL, or max_tokens == 0, return -1.input is empty (``), return 0.-1 without truncating.max_tokens, return -1.tokens and return the number of tokens parsed.char tokens[4][64];
safe_tokenize("user:admin:read", ':', tokens, 4); // returns 3, tokens = {"user", "admin", "read"}
input: string to split; delimiter: char separator; tokens: 2D char array [max_tokens][64]; max_tokens: maximum token slots.
Returns token count on success, -1 on invalid inputs or bounds violation.
C11 freestanding. No malloc. Token slots are strictly 64 bytes.
#include <stddef.h>
/* Split input by delimiter into tokens[][64] up to max_tokens.
Return token count on success, or -1 if any token exceeds 63 chars,
if tokens exceed max_tokens, or if inputs are NULL. */
int safe_tokenize(const char *input, char delimiter, char tokens[][64], size_t max_tokens) {
(void)input; (void)delimiter; (void)tokens; (void)max_tokens;
return -1;
}
Overwriting tokens array past max_tokens; truncating long tokens instead of failing; forgetting NUL terminator.
Empty string returns 0; consecutive delimiters produce empty tokens; token of exactly 63 chars fits; token of 64 chars fails.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.