C String strdup() Function

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 5 Examples
<string.h> (POSIX)

What You’ll Learn

The strdup() function creates a heap-allocated duplicate of a C-string. It handles malloc and copying in one call so you get an independent string you can modify and later release with free().

01

Duplicate

New heap copy.

02

malloc

Auto alloc.

03

free()

You release.

04

NULL

On failure.

05

POSIX

Not ISO C.

06

vs strcpy

You pick buf.

Definition and Usage

strdup stands for string duplicate. It computes strlen(s) + 1, allocates that many bytes, copies every character including '\0', and returns the new pointer. The source string can be a literal, a stack buffer, or any valid C-string.

Because memory comes from the heap, the duplicate outlives local arrays when you store the pointer elsewhere. That convenience comes with responsibility: every successful strdup needs a matching free.

💡
Beginner Tip

strdup is POSIX—not guaranteed in strict ISO C. On Linux and macOS it lives in <string.h>. On Windows with MSVC, use _strdup(). When portability matters, wrap it or use malloc(strlen(s)+1) plus strcpy.

📝 Syntax

POSIX declaration:

C
char *strdup(const char *s);

Headers

  • POSIX (Linux, macOS)#include <string.h>
  • Free memory#include <stdlib.h> for free()
  • Windows (MSVC)#include <string.h> and _strdup(s)

Parameter

  • s — null-terminated string to duplicate.

Return Value

  • Pointer to the newly allocated copy on success.
  • NULL if allocation fails.

⚡ Quick Reference

OperationCodeNotes
Duplicatecopy = strdup(s);Check for NULL
Releasefree(copy);After last use
Bytes allocatedstrlen(s) + 1Includes '\0'
Manual equivalentmalloc + strcpyPortable fallback
vs strcpystrdup allocatesstrcpy needs your buffer
Duplicate
char *p = strdup(s);

Heap copy

Check
if (p == NULL) { ... }

OOM safe

Free
free(p); p = NULL;

No leak

Windows
_strdup(s)

MSVC name

Examples Gallery

Compile on Linux or macOS with gcc strdup.c -std=c11 -o strdup. Examples use POSIX strdup; see portability notes for Windows.

📚 Getting Started

Duplicate a string, print it, and free the allocated memory.

Example 1 — Basic Duplication

Copy "Hello, C!" to the heap with strdup.

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

int main(void) {
    const char *original = "Hello, C!";
    char *copy = strdup(original);

    if (copy != NULL) {
        printf("Original: %s\n", original);
        printf("Copied:   %s\n", copy);
        free(copy);
    } else {
        fprintf(stderr, "Memory allocation failed.\n");
        return 1;
    }

    return 0;
}

How It Works

strdup allocates 10 bytes (9 characters plus '\0'), copies the text, and returns the new address. free(copy) returns that memory to the system.

Example 2 — Modify the Copy Safely

Change the duplicate without affecting the original literal.

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

int main(void) {
    const char *label = "Version 1";
    char *editable = strdup(label);

    if (editable == NULL) {
        return 1;
    }

    editable[8] = '2';

    printf("Original: %s\n", label);
    printf("Edited:   %s\n", editable);

    free(editable);
    return 0;
}

How It Works

The literal label is read-only. The heap copy from strdup is writable, so changing a digit updates only the duplicate.

📈 Practical Patterns

Error handling, portable fallback, and comparison with strcpy.

Example 3 — Handle Allocation Failure

Always test the pointer returned by strdup.

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

char *duplicate_or_exit(const char *s) {
    char *p = strdup(s);
    if (p == NULL) {
        fprintf(stderr, "Out of memory duplicating: %s\n", s);
        exit(1);
    }
    return p;
}

int main(void) {
    char *name = duplicate_or_exit("CodeToFun");
    printf("Hello, %s!\n", name);
    free(name);
    return 0;
}

How It Works

When malloc fails inside strdup, the function returns NULL. Wrapping the call in a helper keeps main code clean and avoids dereferencing a null pointer.

Example 4 — Portable Manual Duplicate

Implement the same behavior with malloc and strcpy.

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

char *my_strdup(const char *s) {
    size_t n = strlen(s) + 1;
    char *p = malloc(n);

    if (p != NULL) {
        strcpy(p, s);
    }

    return p;
}

int main(void) {
    const char *src = "Portable copy";
    char *dup = my_strdup(src);

    if (dup != NULL) {
        printf("%s\n", dup);
        free(dup);
    }

    return 0;
}

How It Works

This is exactly what typical strdup implementations do internally. Use this pattern on platforms without strdup in the library.

Example 5 — strdup() vs strcpy()

strcpy needs a buffer you size; strdup sizes and allocates for you.

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

int main(void) {
    const char *msg = "Same text, different storage";

    /* strcpy: you provide the buffer */
    char stack_buf[64];
    strcpy(stack_buf, msg);

    /* strdup: heap buffer allocated for you */
    char *heap_copy = strdup(msg);

    if (heap_copy != NULL) {
        printf("Stack: %s\n", stack_buf);
        printf("Heap:  %s\n", heap_copy);
        free(heap_copy);
    }

    return 0;
}

How It Works

Both produce equal C-strings. Stack storage ends when the function returns unless you copy the pointer elsewhere. Heap storage from strdup persists until you free it.

🚀 Common Use Cases

  • Save user input — duplicate a line read into a temporary buffer.
  • Struct ownership — store heap copies of name fields in dynamic records.
  • API handoff — return a newly allocated string the caller must free.
  • Config values — copy defaults before parsing modifies them.
  • Linked lists — attach duplicated string data to nodes.

🧠 How strdup() Works

1

Measure strlen(s)

Compute bytes needed including '\0'.

Size
2

malloc(n)

Return NULL if allocation fails.

Alloc
3

Copy with strcpy/memcpy

Write full string into new buffer.

Copy
=

char* copy

Independent heap string—caller calls free.

📝 Notes

  • POSIX extension—verify availability or provide a fallback.
  • Always free() the returned pointer when done.
  • Do not free the original s unless you allocated it separately.
  • Passing NULL to strdup is undefined—guard if needed.
  • Do not mix free with non-malloc allocators unless documented.

⚡ Optimization

strdup allocates every time. For many duplicates of the same short strings, a string pool or intern table may reduce fragmentation. For occasional copies, strdup is simple and fast enough.

Conclusion

strdup() duplicates a C-string on the heap in one step. Check for NULL, use the copy freely, and call free() when finished. When strdup is unavailable, use malloc plus strcpy.

Continue with strerror() for system error messages, or review strcpy() for in-buffer copies.

💡 Best Practices

✅ Do

  • Check strdup for NULL
  • Call free exactly once on the duplicate
  • Set pointer to NULL after free if reused
  • Use for unknown-length strings needing heap lifetime
  • Provide a manual fallback on embedded toolchains without strdup

❌ Don’t

  • Leak duplicates by skipping free
  • Double-free the same pointer
  • Assume strdup exists on every C compiler
  • Free the source string thinking it was duplicated in place
  • Use strdup when a small stack buffer would suffice

Key Takeaways

Knowledge Unlocked

Five things to remember about strdup()

Use these points when duplicating strings in C.

5
Core concepts
📝 02

free()

Your job.

Memory
🔢 03

NULL

OOM check.

Safety
📈 04

Independent

Modify copy.

Use case
💬 05

vs strcpy

You alloc.

Compare

❓ Frequently Asked Questions

strdup() allocates heap memory large enough for a copy of the source string (including the null terminator), copies the bytes, and returns a pointer to the new string. The original string is not modified.
char* strdup(const char* s); On POSIX systems include <string.h>. You also need <stdlib.h> for free(). Pass a valid null-terminated C-string as s.
You do. Call free() on the pointer returned by strdup() when you no longer need the duplicate. Forgetting to free causes a memory leak.
It returns NULL if malloc fails (out of memory). Always check the result before using or dereferencing the copy.
strdup() is a POSIX function, widely available on Linux and macOS. It is not part of ISO C. Microsoft C provides _strdup() in <string.h>. You can also implement it with malloc and strcpy.
strcpy() copies into a buffer you provide—it does not allocate. strdup() allocates a new buffer on the heap and copies for you. Use strdup when you need an independent copy whose size you do not know ahead of time.
Did you know?

GNU systems also provide strndup(s, n), which duplicates at most n bytes—handy when copying untrusted input with a length cap. It still allocates n+1 or less and must be freed like strdup.

Continue the String Functions Series

Duplicate strings on the heap with strdup(), then learn system messages with strerror().

Next: strerror() →

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