This project has been created as part of the 42 curriculum by alauer.
Table of Contents
- Description
- Instructions
- Resources
- Documentation
The libft project is an educational project of the 42 curriculum to deepen foundational knowledge of C coding. The project consists of writing an essential C library from scratch, first and foremost many functions of standard C libraries, as these are not allowed to be used in most 42 projects. The C lib functions mostly target type conversions, printing, string manipulation and simple memory operations. The recoded functions are complimented by additional functions mostly targeting more advanced memory management and string manipulation, as well as linked lists, function and void pointers. Other parts of library creation like archiving, Makefiles, Header files are also part of the educational scope of this project.
Compilation
make - compile libft
clean - clean object files
fclean - clean object files and library
make re - clean and make
Testing
I recommend https://github.com/FranFrau/Supreme-Tester-Libft. It's a combination of https://github.com/Tripouille/libftTester and https://github.com/0x050f/libft-war-machine and has really good coverage of memory leaks and issues as well.
Make- & Headerfile: https://www.cs.colby.edu/maxwell/courses/tutorials/maketutor/ https://www.geeksforgeeks.org/c/header-files-in-c-cpp-and-its-uses/
Void Pointer: https://www.geeksforgeeks.org/c/void-pointer-c-cpp/
Function Pointer: https://www.geeksforgeeks.org/c/function-pointer-in-c/
Linked List: https://medium.com/@Dev_Frank/c-linked-list-singly-linked-list-12aecb168834 https://www.geeksforgeeks.org/c/linked-list-in-c/
Book recommendations: https://nostarch.com/effective-c-2nd-edition
AI (Google Gemini) was used in this project to get a lead on debugging, after I tried debugging with printf, my own tests, the aforementioned testers and gdb. It was specifically not used to write any code.
int ft_isalpha(int c)A function to check if a character is alphabetical.
Parameters:
- c: A character passed as an integer.
Returns:
- Returns 0 if character is not alphabetical and 1 if it is.
Checks via the common ASCII 7-bit character encoding according to ISO 646 as on most systems.
int ft_isdigit(int c)A function to check if a character is a digit.
Parameters:
- c: A character passed as an integer.
Returns:
- Returns 0 if character is not a digit and 1 if it is.
Checks via the common ASCII 7-bit character encoding according to ISO 646 as on most systems.
int ft_isalnum(int c)A function to check if a character is alphanumerical.
Parameters:
- c: A character passed as an integer.
Returns:
- Returns 0 if character is not alphanumerical and 1 if it is.
Checks via the common ASCII 7-bit character encoding according to ISO 646 as on most systems.
int ft_isascii(int c)A function to check if a character is in the common ASCII 7-bit encoding.
Parameters:
- c: A character passed as an integer.
Returns:
- Returns 0 if character is not in the common ASCII table and 1 if it is.
Checks via the common ASCII 7-bit character encoding according to ISO 646 as on most systems.
int ft_isprint(int c)A function to check if a character is printable.
Parameters:
- c: A character passed as an integer.
Returns:
- Returns 0 if character is not printable and 1 if it is.
Checks via the common ASCII 7-bit character encoding according to ISO 646 as on most systems.
size_t ft_strlen(const char *s)A function to measure the length of the string pointed to by s in bytes.
Parameters:
- s: A pointer to a constant string of characters.
Returns:
- The length of the string in bytes.
Iterates through the string using pointer arithmetics to iterate the pointer parameter copy of s forward until it's FALSE ('\0'). Increments a size_t size variable every tick and returns it at the end.
void * ft_memset(void *s, int c, size_t n)A function to fill the first n bytes in a memory area with copies of a chosen character.
Parameters:
- s: A void pointer storing the address of the buffer to be filled.
- c: The character to fill the buffer with, passed as integer.
- n: The size of the buffer passed as unsigned long (size_t).
Returns:
- A void pointer storing the address of the buffer.
Typecasts the address at s by storing it in an unsigned char cp. Iterates through the buffer by comparing a size_t m against n. In each step sets the individual addresses to c. Returns the input pointer.
void ft_bzero(void *s, size_t n)A function to fill the first n bytes in a memory area with zero terminators.
Parameters:
- s: A void pointer storing the address of the buffer to be filled.
- n: How many bytes of data to overwrite.
Iterates through the buffer by comparing a size_t m against n. In each step sets the individual addresses to '\0'.
void * ft_memcpy(void *dest, const void *src, size_t n)A function to copy the first n bytes from the buffer at src to dest.
Parameters:
- dest: A void pointer storing the address of the destination buffer.
- src: A void pointer storing the address of the source buffer.
- n: The number of bytes to be copied.
Returns:
- Returns a void pointer to the address of the source buffer.
The copying takes place by iterating through the buffer and setting and assigning the respective indices. It is assumed they don't overlap. Typecasts s1 and s2 as unsigned chars to read byte by byte, by storing them in new variables p1 and p2.
void * ft_memmove(const void *dest, const void *src, size_t n)A function to copy the first n bytes from the buffer at src to dest.
Parameters:
- dest: A void pointer storing the address of the destination buffer.
- src: A void pointer storing the address of the source buffer.
- n: The number of bytes to be copied.
Returns:
- Returns a void pointer to the address of the source buffer.
Typecasts s1 and s2 as unsigned chars to read byte by byte, by storing them in new variables p1 and p2. The copying takes place by iterating through the buffer and setting and assigning the respective indices. If the dest pointer stores a bigger address than src and src + n would result in a bigger address than dest it is assumed that the buffers overlap. In that case the iteration is done in reverse (i is set to n and decreased to 0).
size_t ft_strlcpy(char *dst, const char *src, size_t size)A function to safely copy as much of the string pointed to by src to the one pointed to by dst as possible.
Parameters:
- dst: Address of the destination buffer.
- src: Address of the source buffer.
- size: Size of the destination buffer.
Returns:
- The needed size for a successful copying, aka len of str.
The function first measures the size of src with ft_strlen. It then calculates the maximum copying size, which equals to size - 1 to guarantee null termination. If the size is 0 or smaller is immediately returns the len of str to indicate that a bigger buffer is needed. As long as the index counter is smaller than the maximum copying length and the index is not '\0' the copying takes place. Then the buffer is NULL terminated and len of src is returned.
size_t ft_strlcat(char *dst, const char *src, size_t size)A function to safely concatenate as much of the string pointed to by src to the one pointed to by dst as possible.
Parameters:
- dst: Address of the destination buffer.
- src: Address of the source buffer.
- size: Size of the destination buffer.
Returns:
- The needed size for a successful concatenation. Either size + len of str or size of dest + size of *src.
The function first measures the size of each string with ft_strlen. It then calculates the maximum concatenation size, which equals to size - len of dest - 1 to make space for a terminating byte. If the size of dst is bigger than the one of src, there is no space for the terminating byte in the buffer and size + length of str is returned to indicate better space requirements. Else as long as the index counter is smaller than the maximum concatenation variable and the source string has not hit the terminator the copying is executed. Finally a terminating byte is appended to dst and the successful size len of dst + len of src is returned.
int ft_toupper(int c)A function to convert a character to uppercase if it's in lowercase.
Parameters:
- c: A character passed as an integer.
Returns:
- Returns the character as integer, converted or not.
Subtracts 0x20 to the character's integer value if it is between 0x61 and 0x7A.
int ft_tolower(int c)A function to convert a character to lowercase if it's in uppercase.
Parameters:
- c: A character passed as an integer.
Returns:
- Returns the character as integer, converted or not.
Adds 0x20 to the character's integer value if it is between 0x41 and 0x5A.
char * ft_strchr(const char *s, int c)A function to find a character in the string pointed to by s.
Parameters:
- s: The address of the string.
- c: The character to scan for, passed as integer.
Returns:
- A char pointer to the first occurrence of the character or NULL if the character is not scanned.
The function iterates through the string by pointer arithmetic increments. The dereferenced value is compared to c. If the increments reach the terminating byte the pointer is returned. Else NULL is returned.
char * ft_strrchr(const char *s, int c)A function to find the last occurrence of a character in the string pointed to by s.
Parameters:
- s: The address of the string.
- c: The character to scan for, passed as integer.
Returns:
- A char pointer to the last occurrence of the character or NULL if the character is not scanned.
The function iterates through the string by use of indexing. First a copy of s is created to typecast s to a non-constant char pointer. The index variable is set to the len of the copy of s - 1 using ft_strlen. c is also cast as char and in the case it's '\0' the address of *p1[i + 1] is returned. Then i is decremented until it matches 0 or cr, in the first case 0 is returned else the address of the character occurrence.
int ft_strncmp(const char *s1, const char *s2, size_t n)A function to compare the first n bytes of the strings at s1 and s2.
Parameters:
- s1: The address of the first string.
- s2: The address of the second string.
- n: 0 or *s3 - *s4
Returns:
- Returns 0 if the strings are identical up to n, or the difference between the first non-matching characters.
Iterates through the strings by decrementing the copy of n. If 0 is passed for n, 0 is immediately returned as it's not guaranteed that s1[0] - s2[0] is 0. Otherwise iteration goes as long as n is TRUE and the dereferenced pointers match. While n acts as indicator for the # of iterations pointer arithmetics and dereferencing are used for the comparison. If n is 0 inside the loop, 0 is returned as well. Otherwise the dereferenced values s3 and s4 are subtracted and returned.
void * ft_memchr(const void *s, int c, size_t n)A function to find a character in the first n bytes of the memory area pointed to by s.
Parameters:
- s: The address of the first byte of the memory area to scan.
- c: The character to scan for, passed as integer.
- n: The number of bytes to be searched.
Returns:
- A void pointer to the first occurrence of the character or NULL if the character is not scanned.
s is typecast by storing it in an unsigned char variable and making a copy as return variable. The buffer is scanned with the index compared against n. If the index matches c cast as unsigned char, the out copy will be set to that address and returned, cast as void pointer.
int ft_memcmp(const void *s1, const void *s2, size_t n)A function to compare the first n bytes from the buffer at s1 to s2.
Parameters:
- s1: A void pointer storing the address of the first buffer.
- s2: A void pointer storing the address of the second buffer.
- n: The number of bytes to be compared.
Returns:
- Returns 0 if equal. A negative value if s2 is bigger and a positive if s1 is bigger. The number is calculated by subtracting the first non-matching character from s2 from the counterpart of s1.
Typecasts s1 and s2 as unsigned chars to read byte by byte, by storing them in new variables p1 and p2. Then runs a counter size_t i against n, continues forward if the indices match, subtracts values and returns in case they don't. If the iteration successfully runs n times 0 is returned.
char * ft_strnstr(const char *big, const char *little, size_t len)A function to search for the occurrence of string little in the string big searching a maximum of len characters.
Parameters:
- big: The address of the big string to be searched.
- little: The address of the little string to be found.
- len: The maximum length of bytes to be searched.
Returns:
- A pointer to the address of the first occurrence of little in big or 0, or big if little is empty.
The function first checks if the little string empty. In this case big is returned in full. Otherwise the function proceeds to a double iteration as long as the first index variable or its sum with the second remain smaller than len. If in the second iteration it runs into the null byte it assumes little to be found and returns a pointer to it's first character. However if little is not found, it returns 0.
int ft_atoi(const char *nptr)A function that takes a string and converts the first sequence of digits found into an integer.
Parameters:
- nptr: A pointer to the string to look for digits in.
Returns:
- The sequence of digits found in the string or NULL.
The atoi function begins with a validity check for the string and returns 0 if it is empty. It then scans the string for leading spaces defined according to the isspace function and skips those. Afterwards it tests for a possible polarity sign and sets an integer to be positive or negative based on the result. The main logic occurs by iterating through the rest of the string with pointer increments, as long as the index is a digit. It would then convert it to the integer value by subtracting 48 and adding it to the integer * 10. In any case the result is multiplied with the polarity and returned.
void * ft_calloc(size_t nmemb, size_t size)A function to allocate memory for a number of members of a specific type and filling it with 0.
Parameters:
- nmemb: The number of members of the buffer to be created.
- size: The size of the members to be allocated for.
Returns:
- A pointer to the newly created buffer, a unique freeable pointer if empty input is passed or NULL.
The ft_calloc function first checks for validity of the input and returns a freeable unique pointer if empty input is passed. It then checks if the multiplication of nmemb * size might result in an overflow, by checking if size is bigger than (size_t)-1 / nmemb. This definition of the SIZE_T_MAX allows for portable handling of the overflow. If an overflow is possible it returns NULL. If everything checks out it uses malloc to allocate nmemb * size. If the allocation fails 0 is returned. It then uses ft_memset to fill the newly allocated buffer with zeros and returns it's address.
char * ft_strdup(const char *s)A function to duplicate a string with variable length.
Parameters:
- s: The address of the string to be duplicated.
Returns:
- A pointer to the duplication buffer.
The function starts by measuring the length of the string using ft_strlen, adding an extra byte for the null terminator and then allocating as much space with malloc. It accounts for failed allocations and then utilizes ft_strlcpy with the allocated buffer size to copy the original string over. It is then returned.
char * ft_substr(char const *s, unsigned int start, size_t len)A function to extract a subtract from the index start and length of len out of s to a newly allocated buffer.
Parameters:
- s: The string for the substring to be extracted from.
- start: The starting index of the substring.
- len: The length of the substring.
Returns:
- A pointer to the new substring buffer, NULL on allocation failure.
This function utilizes ft_strlen for length measurements. The function first checks if the length of s is smaller or equals start, which indicates that there is not enough space is available for the substring or a faulty start index was provided. In this case it returns a freeable empty buffer or NULL if the allocation fails. Otherwise it calculates the total copying length by subtracting start from the length of s. If it finds that the result is bigger than len its gets truncated to len. This ensures only the actual substring length is copied and no empty allocation takes place even if len is bigger than the actual substring or it is incomplete. It also protects against running off the string. This total length is then malloced, returning NULL if the allocation fails. If it is successful ft_strlcpy is used to copy the substring. A pointer to it's address is finally returned.
char * ft_strjoin(char const *s1, char const *s2)A function to join the strings at s1 and s2 together.
Parameters:
- s1: Address of the first string to be joined.
- s2: Address of the second string to be joined.
Returns:
- A pointer to the joined string buffer or NULL on allocation failure.
The function allocates space for a buffer of the combined len of the input buffers, measured with ft_strlen and an extra byte for a terminating byte. If allocation fails it returns NULL. It then uses ft_strlcpy to copy s1 to the buffer and ft_strlcat to then concatenate s2. Finally it returns a pointer to the newly joined string.
char * ft_strtrim(char const *s1, char const *set)A function to trim the characters from set from the start and end of s1.
Parameters:
- s1: The address of the string to be trimmed.
- set: The address of a sequence of characters to be trimmed off.
Returns:
- NULL on allocation failure or a pointer to the newly trimmed string.
The function checks for occurrences of a character from set in the beginning of s1 using ft_strchr and counts up a start index variable every time. It then does the same for a end index variable initially set to ft_strlen of s1 - 1. If the end index is smaller than the start index it is assumed that the indices overlap. This may be the case if set = s1. A unique freeable buffer is allocated in this case and passed returned. If the allocation fails 0 is returned. Otherwise the new trimmed buffer size is calculated by subtracting the start index from end index and 2 extra bytes, one to account for indexing and one for the null byte. The trimmed string is copied over using ft_strlcpy with the start index and buffer size. The trimmed buffer is returned as end result.
char ** ft_split(char const *s, char c)A function to split s into multiple substrings using the delimiter c.
Parameters:
- s: The address of the string to be split.
- c: The delimiting character.
Returns:
- An array of pointers to the newly split strings or NULL if allocation fails.
The function first calls a helper function taking both parameters to allocate space for the parent array. For this it iterates through the string and counts the number of substrings, skipping c along. It then allocates this number of char * pointers plus an extra one for the terminating NULL pointer. If allocation fails, NULL is returned. The newly allocated array of pointers is then returned.
The function then proceeds to another helper function taking the new buffer and the original string, as well as c. Using double iteration again it looks for a substring then allocates memory using malloc for its measured length and copies the string over using ft_strlcpy. This time however if allocation fails, a special cleaner function is called to free all instances of copied strings before the freed allocation. Only after that is 0 returned. The newly split Array is finally returned.
char * ft_itoa(int n)A function to convert an integer into its string representation.
Parameters:
- n: The integer to be converted.
Returns:
- The string representation of n or NULL if allocation fails.
The function starts by handling overflow and 0 input values. It uses a helper function to print out literal hardcoded strings in those cases. Afterwards it proceeds to check for the polarity of the integer. A flag is set for a negative value and the n converted to a positive number. Its length is then measured using integer division. The result is malloc'd with an extra byte for the null terminator, and one more if the polarity flag is set. If allocation fails NULL is returned. The terminating byte is set first and then the integer is broken apart using integer division and converted by adding 48. The string is iterated in reverse and the numbers assigned. If the polarity flag is checked a '-' character is added in front. The newly created string is returned.
char * ft_strmapi(char const *s, char(*f)(unsigned int, char))A function to apply function f to all characters in the string pointed to by s.
Parameters:
- s: The address of the string to be handled.
- f: The address of the function to be applied.
Returns:
- A pointer to the transformed string.
A duplicate of the string is being made, in case it's in write-protected memory. The copy is then being iterated and the function applied to every index. Finally, the copy is returned.
void ft_striteri(char *s, void(*f)(unsigned int, char *))A function to apply function f to all characters in the string pointed to by s.
Parameters:
- s: The address of the string to be handled.
- f: The address of the function to be applied.
Returns:
- A pointer to the transformed string.
The string is then being iterated and the function applied to every index. Finally, the copy is returned.
void ft_putchar_fd(char c, int fd)A function to print a single character c to file descriptor fd.
Parameters:
- c: The character to be printed.
- fd: The file descriptor to be printed to.
void ft_putstr_fd(char *s, int fd)A function to print a string pointed to by s to file descriptor fd.
Parameters:
- s: The address of the string to be printed.
- fd: The file descriptor to be printed to.
The function iterates through the string and uses ft_putchar_fd to print the individual characters.
void ft_putendl_fd(char *s, int fd)A function to print a string pointed to by s followed by a newline to file descriptor fd.
Parameters:
- s: The address of the string to be printed.
- fd: The file descriptor to be printed to.
The function iterates through the string and uses ft_putchar_fd to print the individual characters. It then uses the same function to put a '\0'.
void ft_putnbr_fd(int n, int fd)A function to print the string representation of an integer n to the file descriptor fd.
Parameters:
- n: The integer to be represented.
- fd: The file descriptor to be printed to.
The function calls ft_itoa to convert the integer n to its string representation and then uses ft_putstr_fd to print it.
t_list * ft_lstnew(void *content)A function to create a new node for the linked list t_list.
Parameters:
- content: The address of the data to act as content for the node.
Returns:
- A pointer to the new node or NULL on failed allocation.
The function malloc's space for a t_list and casts the return value to a t_list pointer. If the allocation is failed, NULL is returned. content is assigned to the structs content member and NULL to the next member. A pointer to the new node is returned.
void ft_lstadd_front(t_list **lst, t_list *new)A function to add a node ahead of a list.
Parameters:
- lst: A pointer to the address of the current head node of a list.
- new: A pointer to the node to be added as new head.
The next member of new is assigned to lst. The address of the new head is then stored in the double pointer representing the head lst.
int ft_lstsize(t_list *lst)A function to measure the length of a linked list of type t_list.
Parameters:
- lst: A node to measure the list from.
Returns:
- The size of the list as an integer.
The function makes a copy of the list and then increases a counter as many times as it can be set to it's next member without it being NULL (the list terminator). It then returns the counter variable.
t_list * ft_lstlast(t_list *lst)A function to return the last node of a list.
Parameters:
- lst: A node of the list, that the last node is to be returned from.
Returns:
- A pointer to the last node of the given list or NULL for invalid input.
The function first checks if the input is valid. If it's empty NULL is returned. It then iterates through the list as long as the nodes next member is TRUE. The first time it's not it returns.
void ft_lstadd_back(t_list **lst, t_list *new)A function to add a node to the back of a list.
Parameters:
- lst: A pointer to the address of the current head of a list.
- new: The new node to be appended.
The function first checks the validity of the input. If lst or new is 0 is returns. If lst is NULL is is set to new and the program stops. Otherwise the output of ft_lstlast on lst is stored and the next member is set to new;
void ft_lstdelone(t_list *lst, void(*del)(void *))A function to free one and only one node and delete its content from a t_list.
Parameters:
- lst: The address of the node to delete.
- del: The function to delete the content.
The function first does input validation. If lst or del is FALSE it stops the program. Otherwise it calls del on the content member and then frees the node with free.
void ft_lstclear(t_list **lst, void(*del)(void *))A function to delete a node and all following lists and the corresponding content from a t_list.
Parameters:
- lst: A pointer to the address of a node of the list.
- del: The function to delete the content of the node.
The function first does input validation. If lst or del is FALSE it stops the program. Otherwise it makes a copy of the list and iterates through it as long as the head is TRUE. It makes a temporary copy of the next member, deletes the data pointed to by content if existing with del and frees the node. It then sets the address stored previously as next node to operate on. Finally it sets lst to NULL.
void ft_lstiter(t_list *lst, void(*f)(void *))A function to apply function f to each content of each node in lst.
Parameters:
- lst: The list to be worked on.
- f: The function to be applied.
The function first does input validation. If lst or f is FALSE it stops the program. Otherwise it makes a copy of the list and iterates through it as long as the head is TRUE. It makes a temporary copy of the list and iterates through it. It applies f to the content and changes to the node at the stored address.
t_list * ft_lstmap(t_list *lst, void *(*f)(void *), void(*del)(void *))A function to apply function f to each content of each node in lst. A new list is created with the changed content and returned.
Parameters:
- lst: The list to be worked on.
- f: The function to be applied.
- del: A function to clear content, if allocation fails.
Returns:
- The new list, or NULL if node creation fails.
The function first does input validation. If lst or del or f is FALSE it stops the program. Otherwise it makes a copy of the list and iterates through it as long as the head is TRUE. It makes a temporary copy of the list and iterates through it. It applies f to the content and creates a new node with ft_lstnew and the modified content. If the node creation fails, it deletes the stored content and clears the new list with ft_lstclear and returns NULL. If the creation is successful, ft_lstadd_back is called to append the new node and the focus is changed to the node at the temporarily stored address.