C++ strndup() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
<cstring>

Definition

strndup (POSIX) allocates a copy of at most n characters from a C-string and adds a terminator.

Not standard C++. Prefer std::string(src, n).

This guide shows the C library helper in a C++ .cpp program with std::cout. Prefer std::string for new text code; keep these APIs for C interop and interviews.

Syntax

POSIX form:

C++
// char* p = strndup(src, n);
// free(p);
CallWhat it does
strndup(s, n)malloc’d copy of at most n chars.

Examples use std::string for a portable demonstration.

Library declarations
C++
char* strndup(const char* s, size_t n); // POSIX

Parameters

ParameterDescription
sSource C-string.
nMaximum characters to copy.

Return Value

Return ValueDescription
char*New buffer or null.

C++ Examples

Example 1 — string Prefix Copy

Take first two characters.

C++
#include <iostream>
#include <string>

int main() {
    const char* src = "CodeToFun";
    std::string t(src, 2);
    std::cout << t << '\\n';
    return 0;
}

How It Works

  1. Constructor copies two chars.
  2. Result is a normal std::string.
  3. Prints Co.

Example 2 — n Larger Than Length

Copy whole short string.

C++
#include <iostream>
#include <string>
#include <cstring>

int main() {
    const char* src = "hi";
    std::size_t n = 10;
    std::string t(src, std::strlen(src) < n ? std::strlen(src) : n);
    std::cout << t << '\\n';
    return 0;
}

How It Works

  1. Source length is 2.
  2. We do not read past the null.
  3. Result is hi.

Example 3 — RAII Copy

std::string frees itself.

C++
#include <iostream>
#include <string>

int main() {
    std::string t("abcdef", 3);
    std::cout << t.size() << '\\n';
    return 0;
}

How It Works

  1. Three characters are taken.
  2. size is 3.
  3. Destructor releases memory automatically.

Frequently Asked Questions

POSIX allocator that copies at most n chars and null-terminates.
No.
std::string(src, n) or string_view.
Yes for the POSIX function.
strdup copies the whole string.

Next: strpbrk()

Keep going through the string functions. Find the first character that matches any in a set.

strpbrk() 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.

14 people found this page helpful