1. Home
  2. Computer Science MCQs
  3. C Programming
  4. char dst[4]; strncpy(dst, "abcd", 4); is executed. What is…

Added 30 Nov -0001

char dst[4]; strncpy(dst, "abcd", 4); is executed. What is the state of dst afterwards?

  1. The copy is truncated to three bytes and a NUL fills the last position of dst
  2. The call is rejected at run time and dst keeps its previous uninitialised bytes
  3. The four bytes are copied with no terminating NUL, so dst is not a valid string Correct answer
  4. Three bytes are copied and a NUL is appended, since space is always reserved

Correct answer

C. The four bytes are copied with no terminating NUL, so dst is not a valid string

16 views

MCQSEXAM

Explanation

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.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is C? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More C Programming MCQs

Practise all C Programming MCQs

Similar MCQs