The strncpy function is a safer version of strcpy to copy a string from a source to a destination buffer. It takes three arguments, its third argument (n) is the maximum number of characters to copy.
The strncpy function prevents buffer overflow because you put the length of bytes which you want to copy, but the condition is that the destination buffer should have sufficient space to copy the n bytes.
Syntax of strncpy():
The strncpy function copies no more than n characters (characters that follow a null character are not copied) from the array pointed to by “src” to the array pointed to by “dest”.
Note: If copying takes place between objects that overlap, the behavior is undefined.
char *strncpy(char * restrict dest, const char * restrict src, size_t n);
Parameters:
src: It is a pointer to the source string which will be copied.
dest: Pointer to the destination array where the content is to be copied.
n: The first n character copied from src to dest.
Return:
It returns a pointer to the destination string.
Let’s see an example code to understand the functionality of the strncpy function. In this C code, I am copying the string from an array “src” to the array “dest”.
#include <stdio.h> #include <string.h> int main() { char src[] = "Aticleworld"; // The destination string size is 14. char dest[16] = {0}; // copying n bytes of src into dest. strncpy(dest, src, 12); printf("Copied string: %s\n", dest); return 0; }
Output:
Copied string: Aticleworld
Some important points related to the strncpy function:
1. If the source buffer is longer than the number of bytes that you want to copy, then no null character is implicitly appended at the end of the destination buffer.
#include <stdio.h> #include <string.h> int main() { char src[12] = "Aticleworld"; // The destination string size is 14. char dest[12]; // copying 5 bytes of src into dest. strncpy(dest, src, 5); printf("Copied string: %s\n", dest); return 0; }
Output:
Explanation:
You can see printing “Aticl” with some garbage because no trailing null character is available. See the below table for better understanding,
So to resolve this issue we must use add a trailing null character explicitly in the last of the destination buffer.
#include <stdio.h> #include <string.h> int main() { char src[] = "Aticleworld"; // The destination string size is 10. char dest[10]; // copying 5 bytes of src into dest. strncpy(dest, src, 5); dest[5] = '\0'; //Append null character printf("Copied string: %s\n", dest); return 0; }
Output:
2. If the source string is shorter than n characters (number of characters want to copy), then the destination array is padded with zeros until a total of n characters have been written to it.
#include <stdio.h> #include <string.h> int main() { char src[] = "Hi"; // The destination string size is 10. char dest[10]; // copying 5 bytes of src into dest. strncpy(dest, src, 5); printf("Copied string: %s\n", dest); return 0; }
Output:
3. If copying takes place between objects that overlap, the behavior is undefined. So you must avoid the use of strncpy when the memory of source and destination is overlapped. In this situation, you should use memmove.
Note: C11 introduce safer version strncpy is strncpy_s.
You can check the below video to understand the working of strncpy in C programming with example code.
How to make the own strncpy function?
Some times people ask the questions to write a program to copy characters’ source to destination. Also, some times require to create own strncpy function. So let’s create our own strncpy function that copies n characters from source to the destination buffer.
Note: Below function only to understand the working of strncpy. There is a lot of scenarios that is not handled in this function. You can handle the scenario as your requirement and if possible then use the library function.
char* my_strncpy(char* dest, const char* src, unsigned int n) { // return if dest and src is NULL if ((dest == NULL) &&(src == NULL)) return NULL; // take a pointer pointing to the beginning of dest string char* start = dest; // copy first n characters of C-string pointed by src // into the array pointed by dest while (*src && n--) { *dest = *src; dest++; src++; } // null terminate dest string *dest = '\0'; return start; }
Code Analysis:
You can see the highlighted portion of the code. Line number 4 and 5 handle the scenario that source and destination memory must not be NULL.
In line number 8, I am holding the starting address of the destination buffer and I will use it to return because in later line I am incrementing the destination pointer.
In line 12 to 17, we have a while loop, the while loops copy character from source to destination one by one and incrementing the source and destination pointer by 1. Copying stops when source points to the address of the null character (‘\0’) or n become 0.
The statement in line 20, appends a null character (‘\0’) to the string.
Let’s create a small application to test our own strncpy() function.
#include<stdio.h> char* my_strncpy(char* dest, const char* src, unsigned int n) { // return if dest and src is NULL if ((dest == NULL) &&(src == NULL)) return NULL; // take a pointer pointing to the beginning of dest string char* start = dest; // copy first n characters of C-string pointed by src // into the array pointed by dest while (*src && n--) { *dest = *src; dest++; src++; } // null terminate dest string *dest = '\0'; return start; } int main() { char src[] = "Aticleworld"; // The destination string size is 14. char dest[16] = {0}; // copying n bytes of src into dest //Using own strncpy function my_strncpy(dest, src, 12); printf("Copied string: %s\n", dest); return 0; }
Output:
Copied string: Aticleworld
Some questions for you, I want to answer of these questions in the comment box.
Q1) Why should you use strncpy instead of strcpy?
Q2) Is strncpy is safe?
Q3) Is strncpy leading to a segmentation fault. If yes then please describe the scenario.
Q4) Describe the scenario when the behavior of strncpy becomes undefined.
Q5 ) It is good to use strncpy_s.
Recommended Articles for you:
- 10 Best C Programming Books.
- Best mouse for a programmer.
- How to make own memmove function in C
- How to make memcpy function in C
- memmove vs memcpy.
- Use of strxfrm in C.
- Implement vector in C.
- How to make own atoi function
- Difference between memmove and memcpy
- How to pass an array as a parameter?
- Pointer Arithmetic in C.
- void pointer in C.
- A brief description of the pointer in C.
- Dangling, Void, Null and Wild Pointers
- When and how to use array in C?