Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

strdup — dynamically allocated string copy

strdup creates an independent, writable string copy. Check for NULL and release the allocated memory with free.

Version: C23; ISO C23 does not require a POSIX feature-test macro to expose strdup. The repository's C23 compiler flag alone does not establish production C library support.

Syntax

#include <string.h>
char *strdup(const char *s);

strdup, declared in <string.h> in C23, copies a string including its terminating \0 into storage allocated as if by malloc. This is not merely pointer assignment.

The argument s must point to a valid null-terminated string; NULL is invalid. The result points to an independent, writable copy or is NULL if allocation fails. Check before use; afterward, release the copy exactly once with free from <stdlib.h>.

The repository's C23 compiler flag does not establish production runtime library support. The example changes only the copy.

Examples

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

int main(void)
{
    const char *original = "cat";
    char *copy = strdup(original);
    if (copy == NULL) return EXIT_FAILURE;
    copy[0] = 'b';
    printf("%s\n%s\n", original, copy);
    free(copy);
    return EXIT_SUCCESS;
}

Result

cat
bat

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources