networking · advanced · ~18 min · safe pentest lab

Find a free connection slot

Locate the first free slot in a server's per-client table.

Challenge

A threaded server keeps a fixed table of per-client slots and assigns each new connection to a free one. Implement the lookup:

int next_free_slot(const int *slots, int n);

slots[i] is a client fd, or −1 when free. Return the index of the first free slot, or −1 if the table is full.

Why this matters

The simplest concurrency model for a server: one thread per connection.

Input format

slots array of n entries (fd or −1).

Output format

First free index, or −1 if full.

Constraints

Scan left to right and return the first -1. A full table (no -1) returns −1.

Starter code

#include <stddef.h>
/* A server keeps a fixed table of per-client slots; slots[i] is a client fd, or
   -1 when free. Return the index of the first free slot, or -1 if the table is
   full (models accepting a new connection into a worker table). */
int next_free_slot(const int *slots, int n){ (void)slots;(void)n; return -1; }

Common mistakes

Returning the last free slot instead of the first; treating 0 as 'free' (a real fd can be 0 — free is −1).

Edge cases to handle

First slot free → 0; only the last free → its index; none free → −1.

Background lessons

Up next

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