char dst[4]; strncpy(dst, "abcd", 4); is executed. What is the state of dst afterwards?
Correct answer
C. The four bytes are copied with no terminating NUL, so dst is not a valid string
16 views
C. The four bytes are copied with no terminating NUL, so dst is not a valid string
16 views
strncpy copies at most n bytes and appends a NUL only if the source is shorter than n, so a source of exactly n characters leaves the destination unterminated. Passing dst to strlen or printf then reads past the array, which is undefined behaviour. Using snprintf(dst, sizeof dst, "%s", src) always terminates, and memset plus memcpy is the portable idiom for fixed-width fields.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is C? Ask here and get an explanation.