C++ strdup() Function

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

Definition

strdup allocates a new copy of a C-string (POSIX). You must free it later.

It is not a standard C++ function. Prefer std::string for ownership.

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++
// POSIX:
// char* p = strdup(src);
// free(p);
CallWhat it does
strdup(s)malloc’d copy of s, or null on failure.

Examples below use new[]/delete[] to show the same idea portably.

Library declarations
C++
char* strdup(const char* s); // POSIX

Parameters

ParameterDescription
sSource C-string.

Return Value

Return ValueDescription
char*New buffer, or null on allocation failure.

C++ Examples

Example 1 — Duplicate With new[]

Copy a C-string portably.

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

int main() {
    const char* src = "hi";
    char* p = new char[std::strlen(src) + 1];
    std::strcpy(p, src);
    std::cout << p << '\\n';
    delete[] p;
    return 0;
}

How It Works

  1. Allocate length+1 bytes.
  2. strcpy copies including null.
  3. delete[] releases the buffer.

Example 2 — Copied Length

Show strlen of the copy.

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

int main() {
    const char* src = "Code";
    char* p = new char[std::strlen(src) + 1];
    std::strcpy(p, src);
    std::cout << std::strlen(p) << '\\n';
    delete[] p;
    return 0;
}

How It Works

  1. Source has four characters.
  2. Copy has the same length.
  3. Memory is freed.

Example 3 — std::string Owns

Modern alternative.

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

int main() {
    std::string s = "hi";
    std::string t = s;
    std::cout << t << '\\n';
    return 0;
}

How It Works

  1. Copying a std::string duplicates text safely.
  2. No manual free is required.
  3. This is the usual C++ approach.

Frequently Asked Questions

POSIX helper that malloc-copies a C-string.
No.
You—with free() for strdup.
std::string.
strndup copies at most n characters.

Next: strerror()

Keep going through the string functions. Turn an errno code into a message string.

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

8 people found this page helpful