C String strncpy() Function

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
<string.h>

What You’ll Learn

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.

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.

📝 Syntax

Standard C declaration:

C
char *strncpy(char *dest, const char *src, size_t n);

Safe pattern for C-strings

C
strncpy(dest, src, sizeof(dest) - 1);
dest[sizeof(dest) - 1] = '\0';

Parameters

  • dest — destination buffer (must have room for at least the bytes written).
  • src — source null-terminated string.
  • n — maximum number of bytes to copy from src (including padding behavior).

Return Value

  • Returns dest (pointer to the destination buffer).

Header

  • #include <string.h>

⚡ Quick Reference

srcnResult in destNull-terminated?
"Hello, World!"10"Hello, Wor" (needs manual '\0')Only if you add it
"Hi"8"Hi" + 6 padding '\0' bytesYes (padded)
"CodeToFun"sizeof(dest)-1Full text if buffer fitsYes with forced byte
safe capsizeof(dest) - 1then dest[sizeof(dest)-1]='\0'Recommended
Copy n
strncpy(dest, src, n);

At most n

Force null
dest[sz-1] = '\0';

After copy

Full copy
strcpy(dest, src)

No limit

Modern
snprintf(dest, sz, "%s", src)

Preferred

Examples Gallery

Compile with gcc strncpy.c -std=c11 -o strncpy. Every example that prints a string shows explicit null-termination when needed.

📚 Getting Started

Copy a fixed number of characters and terminate the result yourself.

Example 1 — Copy the First 10 Characters

From "Hello, World!", take only ten bytes and add '\0'.

C
#include <stdio.h>
#include <string.h>

int main(void) {
    char destination[20];
    const char *source = "Hello, World!";

    strncpy(destination, source, 10);
    destination[10] = '\0';

    printf("Copied String: %s\n", destination);

    return 0;
}

How It Works

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;
}

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.

C
#include <stdio.h>
#include <string.h>

int main(void) {
    char dest[8];
    const char *src = "Hi";

    strncpy(dest, src, sizeof(dest));

    printf("Text: [%s]\n", dest);
    printf("Length after strncpy: %zu\n", strlen(dest));

    return 0;
}

How It Works

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;
}

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.

C
#include <stdio.h>
#include <string.h>

int main(void) {
    char full[32];
    char partial[32];
    const char *src = "CodeToFun";

    strcpy(full, src);

    strncpy(partial, src, 4);
    partial[4] = '\0';

    printf("strcpy:   [%s]\n", full);
    printf("strncpy:  [%s]\n", partial);

    return 0;
}

How It Works

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.

🚀 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.

📝 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.

⚡ 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.

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.

💡 Best Practices

✅ Do

  • Use sizeof(dest) - 1 as n for char arrays
  • Set dest[sizeof(dest) - 1] = '\0' after copying
  • 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

Key Takeaways

Knowledge Unlocked

Five things to remember about strncpy()

Use these points when copying strings with a byte limit.

5
Core concepts
⚠️ 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.

Continue the String Functions Series

Copy safely with strncpy(), then learn prefix fill with strnset().

Next: strnset() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful