Simvik

Bounded string copy

Copy a string into a fixed buffer, truncating safely. A medium embedded C problem (Arrays and strings), run and graded in the browser.

medium · Arrays and strings · strings · buffer-overflow

Copy src into the buffer dst, which holds size bytes in total.

  • Copy at most size - 1 characters and always terminate the result, unless size is 0, in which case write nothing.
  • Return the length of src, so the caller can detect truncation by comparing the result with size.

Starter code

size_t safe_copy(char *dst, size_t size, const char *src) {
  // Never write more than `size` bytes, and always terminate when size > 0.
  return 0;
}

Example tests

Fits

char d[8];
size_t n = safe_copy(d, sizeof d, "abc");
printf("%s %u\n", d, (unsigned)n);

Expected output:

abc 3

Truncated

char d[4];
size_t n = safe_copy(d, sizeof d, "abcdefgh");
printf("%s %u\n", d, (unsigned)n);

Expected output:

abc 8

Learn it first

  • Arrays and strings · Decay, bounds, safe copying, and parsing and formatting without the heap.

More Arrays and strings problems