Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

strndup — dynamically allocated, length-limited copy

strndup creates an independent string from at most size initial characters of an array, adding a null terminator. Check the result and release it with free.

Version: C23; repository compiler flag, production runtime not attested

Syntax

#include <string.h>
char *strndup(const char *s, size_t size);

strndup, declared in <string.h>, creates a copy in storage allocated as if by malloc. It copies at most size characters from s, stopping earlier at \0. The result always has a \0 terminator; the limit excludes that terminator.

The source need not be null-terminated if it contains at least size readable characters. Otherwise, a terminator must occur within accessible storage before the limit is reached. The limit does not repair an invalid pointer. Do not assume the result has capacity size + 1 when copying stopped earlier.

On allocation failure, the function returns NULL. Check the result before using it and release a successful copy with free. Unlike strdup, strndup limits the number of copied characters.

The function belongs to C23. The repository compiler flag does not attest availability in the production runtime; suitable headers and library support are also required. The example deliberately uses an array without a terminator.

Examples

#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    const char data[] = {'h', 'e', 'l', 'l', 'o'};
    char *copy = strndup(data, 3);
    if (copy == NULL) return EXIT_FAILURE;
    puts(copy);
    free(copy);
    return EXIT_SUCCESS;
}

Result

hel

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