ft_strdup — Duplicate a String
Allowed functions: malloc
Reproduce the behavior of the function strdup (man strdup).
char *ft_strdup(char *src);
Solution
Download ft_strdup.c#include <stdlib.h>
char *ft_strdup(char *src) {
int i = 0;
while (src[i])
i++;
char *dup = malloc(sizeof(char) * (i + 1));
if (!dup)
return (NULL);
i = 0;
while (src[i]) {
dup[i] = src[i];
i++;
}
dup[i] = '\0';
return dup;
}
How It Works
Goal: Create a heap-allocated copy of a string.
Approach: Measure the string length, allocate memory with malloc, then copy every character manually.
Step by step:
- Count the length of
srcby iterating until the null terminator. - Allocate
length + 1bytes withmalloc(the extra byte is for the null terminator). - If
mallocfails, returnNULL. - Copy each character from
srctodupin a loop, then null-terminatedup.
Key concept: Dynamic memory allocation with malloc and the responsibility to allocate the right size (including the null terminator).