The strncpy() function copies at most n bytes from a source string into a destination buffer. It is the bounded cousin of strcpy(), but its null-termination rules trip up many beginners—this tutorial shows how to use it safely.
01
Bounded
Max n bytes.
02
May truncate
Cut long src.
03
Null trap
Not always.
04
Zero pad
Short src.
05
string.h
Standard C.
06
vs strcpy
Full copy.
Fundamentals
Definition and Usage
strncpy stands for string n copy. It writes up to n bytes from src into dest. If strlen(src) < n, it copies the source (including its '\0') and fills any remaining space up to n bytes with extra null characters.
If strlen(src) ≥ n, it copies exactly n bytes and does not add a terminating null unless one appeared within those n bytes. That is why you often see dest[sizeof(dest) - 1] = '\0'; immediately after strncpy.
💡
Beginner Tip
For new projects, many teams prefer snprintf(dest, sizeof(dest), "%s", src) because it always null-terminates when the buffer size is passed correctly. Learn strncpy anyway—you will see it in legacy code and interviews.
strncpy copies ten bytes without a trailing null because the source is longer than 10. Writing destination[10] = '\0' makes the buffer a valid C-string for printf.
Example 2 — Recommended Safe Pattern
Copy into a fixed buffer using sizeof(dest) - 1 and force the last byte to null.
C
#include <stdio.h>
#include <string.h>
int main(void) {
char dest[16];
const char *src = "This string is too long for the buffer";
strncpy(dest, src, sizeof(dest) - 1);
dest[sizeof(dest) - 1] = '\0';
printf("%s\n", dest);
return 0;
}
📤 Output:
This string is t
How It Works
At most 15 characters copy into a 16-byte array; byte 15 is always '\0'. The text truncates safely instead of running past the buffer end.
📈 Practical Patterns
Padding behavior, truncation, and comparison with strcpy.
Example 3 — Padding When src Is Shorter Than n
See how strncpy fills unused bytes with null characters.
strncpy writes 'H', 'i', '\0', then pads bytes 3–7 with extra '\0' characters. strlen still reports 2 because it stops at the first null.
Example 4 — Truncation Without Manual Null (Danger)
What goes wrong if you forget to terminate after a long source.
C
#include <stdio.h>
#include <string.h>
int main(void) {
char dest[5];
const char *src = "ABCDEFGH";
/* BAD for printing: n equals buffer size, no room for '\0' */
strncpy(dest, src, sizeof(dest));
/* Fix before use: */
dest[sizeof(dest) - 1] = '\0';
printf("Safe after fix: %s\n", dest);
return 0;
}
📤 Output:
Safe after fix: ABCD
How It Works
With n = 5 and a long source, strncpy fills all five bytes with letters and leaves no null terminator. Overwriting the last byte guarantees printf reads a bounded C-string.
Example 5 — strncpy() vs strcpy()
strcpy always copies the full source; strncpy can stop early.
Use strcpy when the destination is guaranteed large enough. Use strncpy (with manual termination) when you must cap how many bytes are taken from the source.
Applications
🚀 Common Use Cases
Fixed-width fields — legacy record layouts that pad short values with nulls.
Truncated labels — store only the first n characters of a long name.
Bounded copies — when you know dest size and src may be longer.
Reading interview code — recognize the post-copy null assignment pattern.
Kernel / POSIX code — appears in older APIs before snprintf was common.
🧠 How strncpy() Works
1
Copy from src
Take bytes until n reached or src hits '\0'.
Read
2
Pad if short
If src ended before n bytes, write extra '\0' padding.
Fill
3
Stop at n
If src is long, copy n bytes—may omit final null.
Truncate
=
📝
char* dest
Up to n bytes written; verify termination before use.
Important
📝 Notes
Does not guarantee a null-terminated C-string when strlen(src) ≥ n.
Padding with zeros can be slower than necessary for plain text buffers.
Behavior if dest and src overlap is undefined.
Unlike strncat, strncpy does not append—it writes from the start of dest.
snprintf(dest, size, "%s", src) is often clearer for new code.
Performance
⚡ Optimization
Zero-padding up to n bytes can waste cycles when you only need a truncated C-string. Copying with memcpy plus an explicit '\0', or using snprintf, avoids writing hundreds of padding nulls into large fixed fields.
Wrap Up
Conclusion
strncpy() copies at most n bytes and is useful when you understand its padding and termination rules. Always force a null byte when building normal C-strings, and consider snprintf for clearer bounded copies in modern programs.
Continue with bounded string fill using strnset() concepts.
Initialize dest when required by your coding standard
Prefer snprintf for new application code
Check dest size before any string copy
❌ Don’t
Assume strncpy always creates a valid C-string
Pass n = sizeof(dest) without leaving room for '\0'
Use strncpy like memcpy on binary data
Ignore zero-padding cost in hot loops
Confuse strncpy null rules with strncat
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about strncpy()
Use these points when copying strings with a byte limit.
5
Core concepts
📝01
At Most n
Limits copy.
Basics
⚠️02
Null trap
Long src.
Safety
🔢03
Zero pad
Short src.
Behavior
📈04
Safe idiom
sz - 1 + null.
Pattern
💬05
vs strcpy
Full copy.
Compare
❓ Frequently Asked Questions
strncpy() copies up to n bytes from src into dest. If src is shorter than n, it copies src including its null byte and fills the rest of the n-byte block with '\0'. If src is longer than or equal to n, it copies n bytes without adding an extra null terminator.
char* strncpy(char* dest, const char* src, size_t n); Include <string.h>. dest must point to a buffer with room for at least n bytes when you rely on strncpy's padding behavior.
No. If strlen(src) >= n, dest may not be null-terminated. Always add dest[sizeof(dest)-1] = '\0' or dest[n] = '\0' when n is less than the buffer size and you need a valid C-string.
strcpy() copies the entire src until '\0'. strncpy(dest, src, n) copies at most n bytes and may pad with zeros or leave dest unterminated when src is long. strncpy limits how much is read from src but does not by itself guarantee a safe C-string.
When src is shorter than n, strncpy writes additional '\0' bytes up to n total. That behavior comes from old fixed-field APIs. For normal text buffers, prefer copying with snprintf or strcpy after checking size.
strncpy(dest, src, sizeof(dest) - 1); dest[sizeof(dest) - 1] = '\0'; This caps the copy one byte short of the buffer end and forces termination. Many style guides recommend snprintf instead for clarity.
Did you know?
OpenBSD replaced dangerous strcpy/strcat calls with custom strlcpy/strlcat functions that always respect buffer size and null-terminate. Linux and portable C code often use snprintf instead. strncpy remains in the standard for compatibility—know its quirks before using it in production.