C strndup() Function

Beginner
6 min read
Updated: Nov 2026
3 examples
string.h

Definition

In C, strndup() allocates a new string containing at most n characters from a source C-string. It stops earlier when it reaches the source terminator and always adds a new '\0' to the copy.

The result belongs to the caller and must be released with free(). strndup() is specified by POSIX rather than classic ISO C, so availability and feature-test requirements depend on the system.

Syntax

Start with this concrete call, then adjust the values for your buffer.

C
char *copy = strndup(source, 5);
CallWhat it does
strndup(source, 5)Allocates a copy of at most the first five source characters.

Include <string.h> for the declaration and <stdlib.h> for free().

Library declaration
C
char *strndup(const char *s, size_t n);

Parameters

ParameterDescription
sRequired. Null-terminated source string to duplicate.
nMaximum number of source characters to copy, not counting the new terminator.

Return Value

Return ValueDescription
New pointerA heap-allocated, null-terminated copy containing at most n characters.
NULLReturned when memory allocation fails.

C Examples

Example 1 — Duplicate a String Prefix

Keep only the first five characters of a longer source string.

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

int main(void) {
    char *copy = strndup("Programming", 5);

    if (copy == NULL) {
        return 1;
    }
    printf("copy = %s\n", copy);
    free(copy);
    return 0;
}

How It Works

  1. Set the maximum. The limit of five allows only the characters P r o g r.
  2. Allocate enough space. The function reserves six bytes: five characters plus a terminator.
  3. Check allocation. A NULL result is handled before printf.
  4. Release ownership. free(copy) prevents a memory leak.

Example 2 — Source Shorter Than the Limit

When n is larger than the string, copying stops at the existing terminator.

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

int main(void) {
    const char *source = "Cat";
    char *copy = strndup(source, 20);

    if (copy != NULL) {
        printf("%s has length %zu\n", copy, strlen(copy));
        free(copy);
    }
    return 0;
}

How It Works

  1. Read a valid C-string. The source terminator appears after three characters.
  2. Stop before the maximum. strndup does not read twenty characters when the string ends sooner.
  3. Create an exact copy. The allocated result contains Cat and its own terminator.
  4. Measure the result. strlen(copy) reports three, not the limit of twenty.

Example 3 — Copy a Bounded Field

Use a measured field length to create an independent string.

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

int main(void) {
    const char record[] = "blue,green";
    const char *comma = strchr(record, ',');
    size_t field_len = comma ? (size_t)(comma - record) : strlen(record);
    char *field = strndup(record, field_len);

    if (field == NULL) return 1;
    printf("first field = %s\n", field);
    free(field);
    return 0;
}

How It Works

  1. Locate the boundary. strchr finds the comma between the two fields.
  2. Calculate a safe length. Pointer subtraction gives four characters before the comma.
  3. Duplicate only that range. strndup copies blue and adds '\0'.
  4. Use an independent value. The new field remains a normal string until it is freed.

Frequently Asked Questions

It allocates a null-terminated copy of at most n characters from a source string.
Yes. A successful result has its own null terminator even when the source is longer than n.
Yes. The returned string is heap allocated and must be passed to free().
Copying stops at the source terminator, so the result contains the complete shorter string.
No. It is a POSIX function and may need a feature-test macro or a portable replacement.

Next: strnset()

Replace up to n characters in a writable string.

strnset() tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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.

9 people found this page helpful