Skip to main content

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:

  1. Count the length of src by iterating until the null terminator.
  2. Allocate length + 1 bytes with malloc (the extra byte is for the null terminator).
  3. If malloc fails, return NULL.
  4. Copy each character from src to dup in a loop, then null-terminate dup.

Key concept: Dynamic memory allocation with malloc and the responsibility to allocate the right size (including the null terminator).