cybersecurity · intermediate · ~15 min

Escape single quotes

Implement SQL single-quote escaping safely.

Challenge

Apply the SQL single-quote escaping rule — doubling each ' — into a bounded output buffer, as a last-resort defence when prepared statements aren't available.

Task

Implement int escape_quotes(const char *in, char *out, int outsz) that copies in into out, replacing every single quote ' with two (''). NUL-terminate out and return the output length (excluding the NUL), or -1 if the result would not fit in outsz.

Input

  • in: a fixed NUL-terminated string the grader provides.
  • out: the destination buffer.
  • outsz: the size of out in bytes.

Output

Returns the length of the escaped string (excluding the NUL), or -1 if it would overflow outsz.

Example

escape_quotes("O'Brien", out, 32)   ->   8,  out = "O''Brien"
escape_quotes("a'b'c", out, 4)      ->   -1  (won't fit)

Edge cases

  • A string with no quotes is copied unchanged.
  • Reserve room for the doubled quote and the NUL; return -1 before overflowing.

Rules

  • Quote-doubling is a fallback; parameterised queries remain the correct fix.

Input format

A fixed NUL-terminated string in, a destination out, and its size outsz.

Output format

The escaped length excluding the NUL, or -1 if it would not fit.

Constraints

Double every single quote; NUL-terminate; return -1 before overflowing outsz.

Starter code

int escape_quotes(const char *in, char *out, int outsz) {
    /* TODO */
    return -1;
}

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