In C programming, duplicating a portion of an existing string is a common requirement. Rather than duplicating an entire null-terminated string, it is often preferable to restrict the number of characters copied to a defined boundary. This approach helps avoid unnecessary memory usage.
The strndup function, defined by POSIX, provides a convenient way to duplicate up to a specified number of characters from a string. It allocates memory for the new string, copies at most the given length, and guarantees null termination. This makes it useful for working with partial string data. Since strndup is not available on Windows by default, a compatible implementation can be provided manually.
The following example demonstrates how to create a length-limited duplicate of a string:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <errno.h>
char *strndup(const char *str, size_t size) {
const size_t len = strnlen(str, size);
char *result = malloc(len + 1);
if (result == NULL) {
errno = ENOMEM;
return NULL;
}
result[len] = '\0';
memcpy(result, str, len);
return result;
}
#endif
int main() {
const char *s1 = "Hello world";
char *s2 = strndup(s1, 5);
printf("%s\n", s2); // Hello
free(s2);
return 0;
}
In this example, only the first five characters of the source string are duplicated, resulting in the output "Hello". The allocated memory is released afterward to prevent memory leaks.
Leave a Comment
Cancel reply