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.
malloc() + copy helper remains the most portable approach.char *copy = strdup(source); // C23; historically POSIX
The returned allocation must be released with free() when it is no longer needed.
#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;
}
#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;
}
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.