Multiple choice technology security

The options show various uses of strncpy. Choose which use of strncpy is most secure while not wasting storage space at dst? Src is an untrusted input obtained from an external source.

  1. strncpy(dst,src,len(dst))

  2. strncpy(dst,src,len(src)+1)

  3. strncpy(dst,src,len(dst)+1)

  4. strncpy(dst,src,len(dst)-1)

Reveal answer Fill a bubble to check yourself
D Correct answer
Explanation

strncpy(dst,src,len(dst)-1) leaves room for the null terminator. strncpy does not guarantee null-termination if src is longer than len-1, so reserving the last byte ensures safety. Option A overflows. Option C uses dst size instead of dst-1. Option B uses src+1 which may overflow dst.