Notes

42 (I): libft, building the toolbox

The first 42 project: rewriting basic C functions from scratch without libraries.

2 min read

The first thing you learn at 42 is that nothing is prepared for you. No printf, no strlen, no libraries (a collection of functions other people have already written): if you need it, you write it yourself. And the first assignment of the course, libft, is exactly that: rewriting a large part of the C standard library from scratch. A heads-up before we start: as a rule of the school I don't share project code, so in this series I'll explain the approach, the problems, and what I took away from it — never the solution.

The problem

On paper, rewriting well-known functions sounds tedious but simple. In practice, it's the project where I learned the most fundamentals in one go. The required list ran to over fifty functions: memory (memset, memcpy, calloc...), strings, character conversion, and, as an optional part, linked lists (chains of data where each piece points to the next). Each one with its own edge cases: empty strings, blocks that don't line up, sizes that exceed what you asked for. And above all, the real underlying theme: really understanding malloc — when it allocates memory, when you need to free it, and what happens when you forget.

How I approached it

I split the work into three blocks: first the shorter memory and string functions, then the ones that build new things (substr, split, strjoin, itoa), and finally the bonus with linked lists. Everything compiles into a static library (a file that's attached to the program at compile time) using a Makefile — the file that tells it how to compile everything — and that was also a learning experience: rules, dependencies, and an fclean that leaves everything tidy. As I went along, I tested each function with my own main for testing, because a function that compiles isn't a function that works. The repository, 42_libft, ended up with the code in src/, the header in include/, and the Makefile at the root; I later merged it into the general course repository, 42_Cursus.

What I took away

Two things. The first: I'll never look at strlen the same way again. Behind every mundane function there are decisions about memory and types that I now understand. The second: discipline. The school's rules enforce a strict style and require managing all memory without leaks (memory that's allocated and never returned); it's painful at first, but after a couple of weeks you do it without thinking. libft has nothing glamorous about it: nobody will see this library outside of class. But it's the toolbox I've used to write everything that came after — the next step was reading files with get_next_line, reading files line by line — and you can feel its quality every time a new project compiles on the first try.