strdup() in C and Portable String Duplication

strdup() allocates memory for a copy of a null-terminated string and returns a pointer to the new copy. It was widely available through POSIX before being added to the C standard in C23.

Version note: for projects targeting older ISO C versions such as C11 or C17, a small malloc() + copy helper remains the most portable approach.

strdup() Syntax Top ↑

char *copy = strdup(source);  // C23; historically POSIX

The returned allocation must be released with free() when it is no longer needed.

Portable Duplicate Function for C11/C17 Top ↑

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

char *duplicate_string(const char *source) {
    size_t length = strlen(source) + 1;
    char *copy = malloc(length);

    if (copy != NULL) {
        memcpy(copy, source, length);
    }

    return copy;
}

int main(void) {
    const char *original = "plus2net";
    char *copy = duplicate_string(original);

    if (copy == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }

    printf("Original: %s\n", original);
    printf("Copy: %s\n", copy);

    free(copy);
    return 0;
}

Duplicate an Array of Names Top ↑

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

char *duplicate_string(const char *source) {
    size_t length = strlen(source) + 1;
    char *copy = malloc(length);

    if (copy != NULL) {
        memcpy(copy, source, length);
    }

    return copy;
}

int main(void) {
    const char *names[] = {"Alice", "Bob", "Charlie"};
    char *copies[3] = {NULL, NULL, NULL};

    for (size_t i = 0; i < 3; i++) {
        copies[i] = duplicate_string(names[i]);

        if (copies[i] == NULL) {
            printf("Allocation failed.\n");

            for (size_t j = 0; j < i; j++) {
                free(copies[j]);
            }

            return 1;
        }
    }

    for (size_t i = 0; i < 3; i++) {
        printf("%s\n", copies[i]);
        free(copies[i]);
    }

    return 0;
}




plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer