This project has been created as part of the 42 curriculum by irabelo.
In this project, I implement my own versions of functions from the C standard library, together with additional functions, to understand how they work and to reuse them in future 42 projects.
The main concepts explored are pointers, memory management, string manipulation and linked lists.
The implementation reproduces the behavior of the original libc functions, following the requirements of the mandatory part of the 42 project. It builds the static library libft.a, whose public declarations are available in libft.h.
The library contains the 43 functions required by the subject, organized into three parts. For each group of functions, the prototypes are listed as declared in libft.h, followed by the description and the return value of each function.
Reimplementations of libc functions with the same prototypes and behavior as the originals, as described in their man pages. Each name starts with the ft_ prefix: for example, strlen() becomes ft_strlen(). As required by the subject, the prototypes do not use the restrict qualifier.
These functions rely on no external functions, except ft_calloc() and ft_strdup(), which allocate memory with malloc().
Prototypes:
int ft_isalpha(int c);
int ft_isdigit(int c);
int ft_isalnum(int c);
int ft_isascii(int c);
int ft_isprint(int c);
int ft_toupper(int c);
int ft_tolower(int c);| Function | Description | Return Value |
|---|---|---|
ft_isalpha() |
Checks whether c is an alphabetic character. |
1 or 0. |
ft_isdigit() |
Checks whether c is a decimal digit. |
1 or 0. |
ft_isalnum() |
Checks whether c is an alphanumeric character. |
1 or 0. |
ft_isascii() |
Checks whether c is a 7-bit ASCII value (0 to 127). |
1 or 0. |
ft_isprint() |
Checks whether c is a printable character, including space. |
1 or 0. |
ft_toupper() |
Converts a lowercase letter to uppercase. | The uppercase letter, or c unchanged. |
ft_tolower() |
Converts an uppercase letter to lowercase. | The lowercase letter, or c unchanged. |
As required by the subject, the classification functions return 1 if the character belongs to the tested class and 0 otherwise.
Prototypes:
void *ft_memset(void *s, int c, size_t n);
void ft_bzero(void *s, size_t n);
void *ft_memcpy(void *dest, const void *src, size_t n);
void *ft_memmove(void *dest, const void *src, size_t n);
void *ft_memchr(const void *s, int c, size_t n);
int ft_memcmp(const void *s1, const void *s2, size_t n);| Function | Description | Return Value |
|---|---|---|
ft_memset() |
Fills the first n bytes of s with the byte c. |
s. |
ft_bzero() |
Sets the first n bytes of s to zero. |
None. |
ft_memcpy() |
Copies n bytes from src to dest. The memory areas must not overlap. |
dest. |
ft_memmove() |
Copies n bytes from src to dest. The memory areas may overlap. |
dest. |
ft_memchr() |
Scans the first n bytes of s for the byte c. |
A pointer to the matching byte, or NULL. |
ft_memcmp() |
Compares the first n bytes of s1 and s2. |
The difference between the first two different bytes, or 0 if the areas are equal. |
Prototypes:
size_t ft_strlen(const char *s);
size_t ft_strlcpy(char *dst, const char *src, size_t size);
size_t ft_strlcat(char *dst, const char *src, size_t size);
char *ft_strchr(const char *s, int c);
char *ft_strrchr(const char *s, int c);
int ft_strncmp(const char *s1, const char *s2, size_t n);
char *ft_strnstr(const char *big, const char *little, size_t len);| Function | Description | Return Value |
|---|---|---|
ft_strlen() |
Calculates the length of s, excluding the null terminator. |
The length of s. |
ft_strlcpy() |
Copies src into dst, a buffer of size bytes, null-terminating the result if size is greater than 0. |
The length of src. |
ft_strlcat() |
Appends src to the end of dst without exceeding a buffer of size bytes. |
The initial length of dst (at most size) plus the length of src. |
ft_strchr() |
Locates the first occurrence of c in s. The terminating '\0' can also be found. |
A pointer to the matching character, or NULL. |
ft_strrchr() |
Locates the last occurrence of c in s. The terminating '\0' can also be found. |
A pointer to the matching character, or NULL. |
ft_strncmp() |
Compares at most n characters of s1 and s2. |
The difference between the first two different characters, or 0 if the strings are equal. |
ft_strnstr() |
Locates the first occurrence of little within the first len characters of big. |
A pointer to the occurrence, big if little is empty, or NULL. |
Prototypes:
int ft_atoi(const char *nptr);
void *ft_calloc(size_t nmemb, size_t size);
char *ft_strdup(const char *s);| Function | Description | Return Value |
|---|---|---|
ft_atoi() |
Converts the initial portion of nptr to an int. |
The converted value. |
ft_calloc() |
Allocates zero-initialized memory for an array of nmemb elements of size bytes each. |
A pointer to the allocated memory, or NULL if the allocation fails. |
ft_strdup() |
Allocates a copy of s. |
The copy, or NULL if the allocation fails. |
Functions that are either not included in the libc or exist there in a different form. Several of them reuse Part 1 functions.
Prototypes:
char *ft_substr(char const *s, unsigned int start, size_t len);
char *ft_strjoin(char const *s1, char const *s2);
char *ft_strtrim(char const *s1, char const *set);
char **ft_split(char const *s, char c);
char *ft_itoa(int n);
char *ft_strmapi(char const *s, char (*f)(unsigned int, char));
void ft_striteri(char *s, void (*f)(unsigned int, char*));
void ft_putchar_fd(char c, int fd);
void ft_putstr_fd(char *s, int fd);
void ft_putendl_fd(char *s, int fd);
void ft_putnbr_fd(int n, int fd);| Function | Description | Return Value |
|---|---|---|
ft_substr() |
Allocates a substring of s that starts at index start and has at most len characters. |
The substring, or NULL if the allocation fails. |
ft_strjoin() |
Allocates a new string with s2 appended to s1. |
The new string, or NULL if the allocation fails. |
ft_strtrim() |
Allocates a copy of s1 without the characters from set at its beginning and end. |
The trimmed string, or NULL if the allocation fails. |
ft_split() |
Allocates an array of the strings obtained by splitting s at the delimiter c. The array ends with NULL. |
The array of strings, or NULL if any allocation fails. |
ft_itoa() |
Allocates a string representing the integer n. |
The string, or NULL if the allocation fails. |
ft_strmapi() |
Allocates a new string built by applying f to each character of s and its index. |
The new string, or NULL if the allocation fails. |
ft_striteri() |
Applies f to each character of s and its index. Characters are passed by address, so they can be modified in place. |
None. |
ft_putchar_fd() |
Writes the character c to the file descriptor fd. |
None. |
ft_putstr_fd() |
Writes the string s to fd. |
None. |
ft_putendl_fd() |
Writes the string s to fd, followed by a newline. |
None. |
ft_putnbr_fd() |
Writes the integer n to fd in decimal. |
None. |
These functions operate on t_list, declared in libft.h:
typedef struct s_list
{
void *content;
struct s_list *next;
} t_list;content— the data stored in the node. Usingvoid *allows any type of data.next— the address of the next node, orNULLif the node is the last one.
Prototypes:
t_list *ft_lstnew(void *content);
void ft_lstadd_front(t_list **lst, t_list *new);
unsigned int ft_lstsize(t_list *lst);
t_list *ft_lstlast(t_list *lst);
void ft_lstadd_back(t_list **lst, t_list *new);
void ft_lstdelone(t_list *lst, void (*del)(void *));
void ft_lstclear(t_list **lst, void (*del)(void *));
void ft_lstiter(t_list *lst, void (*f)(void *));
t_list *ft_lstmap(t_list *lst, void *(*f)(void *), void (*del)(void *));| Function | Description | Return Value |
|---|---|---|
ft_lstnew() |
Allocates a new node whose content is the given value and whose next is NULL. |
The new node, or NULL if the allocation fails. |
ft_lstadd_front() |
Adds the node new at the beginning of the list. |
None. |
ft_lstsize() |
Counts the nodes in the list. | The number of nodes. |
ft_lstlast() |
Finds the last node of the list. | The last node, or NULL if the list is empty. |
ft_lstadd_back() |
Adds the node new at the end of the list. |
None. |
ft_lstdelone() |
Frees the content of a node with del, then frees the node itself, without freeing the next node. |
None. |
ft_lstclear() |
Frees a node and all its successors with del and free(), then sets the list pointer to NULL. |
None. |
ft_lstiter() |
Applies f to the content of each node. |
None. |
ft_lstmap() |
Creates a new list by applying f to the content of each node, using del to clean up if an allocation fails. |
The new list, or NULL if an allocation fails. |
Functions: ft_calloc(), ft_strdup(), ft_substr(), ft_strjoin(), ft_strtrim(), ft_split(), ft_itoa(), ft_strmapi(), ft_lstnew() and ft_lstmap().
These functions return newly allocated memory. The caller must free the results when they are no longer needed. If an allocation fails, they return NULL.
ft_split()— each string must be freed before the array of pointers itself.- List nodes — freed with
ft_lstdelone()orft_lstclear(), which free each node's content through thedelfunction supplied by the caller.
When an allocation fails partway through, the memory already allocated is released, so nothing is leaked:
ft_split()— frees the strings created so far and the array itself.ft_lstmap()— frees the content returned byffor the failed node and clears the new list built so far.
Every function that allocates memory does so through ft_calloc(). New buffers therefore start zero-initialized, and the overflow check is applied in a single place (see ft_calloc() with Zero or Overflow).
Part 1 functions do not check for NULL, like the originals: passing NULL to them is undefined behavior.
Part 2 and Part 3 functions check their pointer arguments: functions that return a pointer return NULL, ft_lstsize() returns 0, and the others do nothing.
ft_substr()— returns an empty string whenstartis beyond the end ofs.ft_strtrim()— returns an empty string when every character ofs1belongs toset.ft_split()— ignores repeated delimiters and delimiters at the ends ofs, so it never creates empty strings. Ifscontains no words, it returns an array containing onlyNULL.
Example:
#include "libft.h"
int main(void)
{
char **words;
size_t i;
words = ft_split(",,ab,,cd,,", ',');
if (!words)
return (1);
i = 0;
while (words[i])
{
ft_putendl_fd(words[i], STDOUT_FILENO);
free(words[i]);
i++;
}
free(words);
return (0);
}Output:
ab
cd
The array contains two strings, followed by NULL.
nmemborsizeequal to0— returnsmalloc(0). On glibc, this is a unique pointer that can be passed tofree(), as the subject requires.nmemb * sizelarger than the maximumsize_t— returnsNULLinstead of allocating a smaller block than requested. The conditionsize > ((size_t)-1) / nmembis checked before multiplying, so the overflow never happens.
ft_itoa()andft_putnbr_fd()— convertntolongbefore negating it, soINT_MINis handled correctly.ft_atoi()— skips leading whitespace (' 'and'\t'to'\r') and accepts a single+or-sign. As with the originalatoi(), a result outside theintrange is undefined behavior.
When dest comes before src, ft_memmove() copies forward with ft_memcpy(). Otherwise, it copies backward, from the last byte to the first, so overlapping bytes are read before they are overwritten.
Example with ft_memmove(buf + 2, buf, 5):
Before: a b c d e . .
Forward copy: a b a b a b a (bytes overwritten before being read)
Backward copy: a b a b c d e (correct result)
- No global variables — as required by the subject.
statichelpers — as required by the subject, helper functions are declaredstatic, which limits them to their own file:ft_count_words(),ft_get_word_len()andft_free_result()inft_split.c, andft_get_alloc_len()inft_itoa.c.- Function reuse — functions build on each other instead of repeating logic. For example,
ft_bzero()callsft_memset(),ft_isalnum()combinesft_isalpha()andft_isdigit(),ft_lstadd_back()usesft_lstlast(), andft_lstclear()callsft_lstdelone()for each node. - Number conversion —
ft_putnbr_fd()uses recursion: it divides the number by 10 repeatedly, stacking the calls on the call stack. As those calls return, the modulo operator (%) yields each digit, which is printed in the correct order.ft_itoa()first counts the characters withft_get_alloc_len(), allocates the string and then fills it from the last digit to the first. - Repository layout — as required by the subject, all files are placed at the root of the repository, where
libft.ais also created with thearcommand.
The following tools are required to compile the project:
cc— a C compiler (e.g., Clang on macOS or GCC on Linux).make— automates the build.ar— creates the static library archive.
From the root directory of the repository, run:
makeThis command compiles the source files with the -Wall -Wextra -Werror flags and creates the static library libft.a.
The following Makefile targets are also available:
| Command | Description |
|---|---|
make or make all |
Compiles the library. |
make clean |
Removes the object files (.o). |
make fclean |
Removes the object files (.o) and libft.a. |
make re |
Removes the generated files and recompiles the library from scratch. |
No installation is required. libft.a is a static library that is linked directly into a C program at compile time, as shown in Usage below.
Include the libft.h header in your C program. For example, a main.c file:
#include "libft.h"
int main(void)
{
char *str;
str = ft_strjoin("Hello, ", "Libft");
if (!str)
return (1);
ft_putendl_fd(str, STDOUT_FILENO);
ft_putnbr_fd(ft_strlen(str), STDOUT_FILENO);
ft_putendl_fd(" characters", STDOUT_FILENO);
free(str);
return (0);
}Assuming main.c is located in the root directory of the repository, compile and link it with the library:
cc -Wall -Wextra -Werror main.c libft.a -o exampleRun the resulting executable:
./exampleOutput:
Hello, Libft
12 characters
Notes:
libft.a— the library linked into the executable. As a static library, it cannot be executed on its own.-o example— sets the name of the resulting executable.
- Linux Manual Pages — used to understand the behavior, return values and edge cases of the functions and features related to the project:
man 3 strlen— length of a string.man 3 memmove— copying between overlapping memory areas.man 3 calloc— zero-initialized allocation.man 3 strlcpy— size-bounded string copy and its return value.man 3 atoi— conversion of a string to an integer.
- 42 Documentation — the project subject was used to check the requirements and allowed functions. The Norm documentation was used as a reference for code style and organization rules.
- De aluno para aluno — YouTube channel used to study the fundamentals of C.
No AI tools were used to write the project's code. AI was used to learn the concepts behind the project.
I used learnharness as a tutor: an AI-agent-based learning tool that builds a knowledge graph and teaches concepts step by step, starting from the learner's current understanding. It did not provide code: its explanations used memory diagrams, pointer layouts and step-by-step graphical explanations, and I implemented the functions myself.
Topics covered:
- Overlapping memory — the overlap between
srcanddestinft_memmove(), to understand why the copy direction matters, before implementing and testing it. - Integer overflow — how
nmemb * sizecan overflow inft_calloc(). - Pointer arrays and linked lists — the pointer-array layout of
ft_split()and the node structure offt_lstmap(), to understand the correct order for freeing memory and what happens when an allocation fails partway through. - Integer conversion — edge cases of
ft_atoi()andft_itoa(), such asINT_MIN, leading whitespace and sign handling.