Safe strncpy Implementation

Medium C Robustness Asked at Cisco
Solve this problem

The standard strncpy does not always null-terminate, which is a classic source of buffer overruns. Write a safe variant that always terminates and reports truncation.

Constraints

  • Signature: `int safe_strcpy(char *dst, size_t dst_size, const char *src)`.
  • Returns 0 on success, -1 if the source was truncated, -2 on invalid arguments.
  • dst must always be null-terminated when dst_size > 0.
  • Must not write more than dst_size bytes.
  • No libc string functions.
  • dst_size == 0 must write nothing at all.
Starter codeC
1#include <stddef.h>2 3int safe_strcpy(char *dst, size_t dst_size, const char *src) {4    // TODO5    return -2;6}