cybersecurity · intermediate · ~15 min · safe pentest lab

Extract the first embedded string

Copy the first qualifying printable run into a bounded output buffer.

Challenge

Pull out the first embedded string, safely:

int first_printable_run(const unsigned char *buf, size_t n, int minlen, char *out, size_t cap);

Find the first printable run of length >= minlen. Copy up to cap-1 of its bytes into out and NUL-terminate. Return the run's full length, or -1 if none. Write to out only when cap>0.

Input format

buf, minlen, and an output buffer out of size cap.

Output format

The full run length (even if truncated in out), or -1.

Constraints

Never write more than cap-1 chars plus the NUL.

Starter code

#include <stddef.h>
/* Find the FIRST printable run (>=minlen). Copy up to cap-1 bytes + NUL into out.
   Return the full run length, or -1 if none. Writes to out only when cap>0. */
int first_printable_run(const unsigned char *buf, size_t n, int minlen, char *out, size_t cap){
    (void)buf;(void)n;(void)minlen; if(cap>0) out[0]='\0'; return -1;
}

Common mistakes

Computing cap-1 when cap==0 (size_t underflow → huge copy → overflow); returning the copied length instead of the true run length.

Edge cases to handle

cap==0: write nothing, still return the length; truncate cleanly for small buffers.

Background lessons

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