How to Use strncpy() and how to write your own strncpy().

how to use strncpy in c

In a program, strncpy prevents from the buffer overflow because you put the length of bytes which you want to copy, but condition is that destination buffer should have the sufficient space to copy the n bytes.

In my view, strncpy is the safer than the strcpy because if the size of source buffer is larger than the number of the bytes which you wants to copy then strncpy does not add the trailing null character in the last of destination buffer.

So to handle this situation, we have to add a trailing null character explicitly in the last of the destination buffer.


Simple program to describe how to use strncpy in your program

In below program, I only copy the “Welcome” from the source buffer to destination buffer using the strncpy a C string library function.


Message = Welcome

Some important points

  • I think, it is better to use strncpy for char array or char pointer instead of unsigned char array or unsigned char pointer.
  • Prefer to use strncpy when you know the length of the source buffer.

In below example, I am using strncpy to copy the source buffer data to destination buffer because here I already know the length of data which want to copy from the source buffer to destination buffer.


Message  = Hi

Note: If you do not add trailing null in the above example then the output will be Hi and some garbage data because here source length larger than n byte you want the copy.

  • In strncpy if the length of the source buffer smaller than the length of byte you want to copy, then append the null character to the destination buffer till n.

In below example, destination buffer contains “bbbb” and source buffer contains “Hi”. When we copy 4 bytes from source to destination buffer then strncpy automatic insert ‘\0’ character after the copy of “Hi”.


Message = H
Message = i
Message =
Message =

  • When source and destination memory overlap then avoid the using of strncpy otherwise you get an undefined result.



How to make the own strncpy function?

In below example copies n bytes from the source buffer to destination buffer. If the length of source buffer is less than n, then insert the null character in the destination buffer till n bytes.

Source Code 1:


Source Code 2:


Leave a Reply