This project has been created as part of the 42 curriculum by acamelo.
This project belongs to the C programming block of the Piscine at 42 Madrid. The central objective of the C 03 module is to rigorously deepen the understanding of pointer behavior, sequential memory structures, and low-level character stream (strings) manipulation.
To achieve this, the project demands the exact replication of several critical functions from the standard <string.h> library (strcmp, strncmp, strcat, strncat, and strstr). Rebuilding these tools from scratch forces the student to understand classic vulnerabilities in C programming, such as buffer overflows, illegal memory segment access (segmentation faults), and the critical importance of the null-terminator byte (\0) as a string boundary sentinel.
All exercises have been developed strictly adhering to the school's Norm, which limits the use of complex loops, forbids unauthorized system functions, and forces code optimization into clean, modular blocks.
The code is designed to be native to Unix/Linux systems. Compilation is performed using the gcc (or clang) compiler along with the most severe optimization and error detection flags from the school standard. These flags immediately transform any warning into a compilation error:
-Wall -Wextra -Werror
Since 42 Piscine projects only require the submission of files containing the pure functions (without a main function), it is necessary to integrate your own test file to verify their behavior against the original C library.
To compile, test, and compare the results of any exercise locally, follow these structured steps:
- Navigate to the desired exercise directory:
cd ex00/
- Create or add your test file (
main.c): Ensure yourmain.cincludes calls to both your function (e.g.,ft_strcmp) and the original one (strcmp) to contrast that return values and memory impacts are identical. - Compile the executable binary:
gcc -Wall -Wextra -Werror ft_strcmp.c main.c -o test_executable
- Execute the test program:
./test_executable
- Memory leak and access verification (Optional but recommended):
valgrind --leak-check=full ./test_executable
The software architecture applied to this module is based on indexed linear scanning and pointer arithmetic. Below is the detailed breakdown and justification of the algorithmic choices made for each section of the project:
-
Mechanics: Both functions implement a synchronous scan. A single iterator advances in parallel over the memory arrays of
s1ands2. Thewhileloop utilizes logical short-circuiting (&&) evaluating two simultaneous exit conditions: that the characters at the current position are identical (s1[i] == s2[i]) and that we have not reached the end of the primary string (s1[i] != '\0'). -
Justification of
ft_strncmp: The inclusion of the size parameterunsigned int nadds a third restrictive condition. The algorithm is designed with an upper bound ofi < n - 1within the advancing loop. This guarantees that the function stops exactly before evaluating the$n$ -th byte, performing the final subtraction outside the loop. This subtle technical choice prevents the pointer from jumping into protected memory zones (out-of-bounds read) in cases wherenis greater than the actual length of the strings. -
Return Value: Instead of returning arbitrary values (such as
-1or1), the algorithm directly subtracts the numerical ASCII values of the mismatched characters (s1[i] - s2[i]). This faithfully replicates the historical behavior of UNIX system libraries.
- Mechanics: The concatenation process is divided into two mandatory sequential phases. The first phase shifts the destination index using a pass-through loop until it positions itself exactly on the null terminator byte (
\0) ofdest. The second phase initiates a cloning loop where each character fromsrcis sequentially overwritten starting from the position of that found null byte. - Justification of Size Control (
ft_strncat): The use of strings without length control is one of the greatest sources of computer vulnerabilities via memory corruption. Inft_strncat, the restrictive variablenbis introduced. The algorithm is justified by ensuring strict copy control using the conditionj < nb. Once the loop is complete or the limit is reached, the algorithm manually injects a null byte (dest[i] = '\0'). This manual operation is fundamental to guarantee that, regardless of the source bytes, the resulting string maintains the structural integrity required by the C language.
-
Mechanics: To find the sub-string
to_findwithin the base textstr, a Naive String Search (Brute Force) approach was selected. The algorithm uses an external main pointer that traversesstr. If the current characterstr[i]matches the beginning of the patternto_find[0], a secondary counterjis initialized to validate the sub-sequence of characters concurrently. -
Justification of the Approach: Although more advanced string matching algorithms exist in computer science (such as Knuth-Morris-Pratt or Boyer-Moore), their implementation requires dynamic memory allocation for jump tables and complex structures. Because the Piscine rules strictly forbid memory allocation functions like
malloc, the Naive String Search algorithm is justified as the most efficient solution, optimal in static memory consumption ($O(1)$ auxiliary space) that best adapts to the constraints imposed by the 42 Norm, keeping the code clean and entirely readable.
- Linux Programmer's Manual - STRCMP(3): Formal POSIX standard specification for string comparison.
- Linux Programmer's Manual - STRCAT(3): Technical details and critical warnings regarding destination buffer sizes.
- Linux Programmer's Manual - STRSTR(3): Substring search behavior and specification of edge cases (e.g., what the function should return if the substring to find is empty).
- The C Programming Language (Kernighan & Ritchie): Chapter 5 (Pointers and Arrays), the fundamental reference for understanding pointer arithmetic applied in these solutions.
In compliance with the transparency regulations of the 42 ecosystem, the ethical and technical use of Artificial Intelligence tools during the development of this repository is detailed below:
- Generation of Test Environments: AI was used to structurally automate massive unit testing scripts embedded within the file comments. This included designing test matrices with extreme edge cases: evaluating pointers with empty strings (
""), identical strings of massive lengths, character mismatches at the first/last byte, and the exact behavior when thenornbparameter equals zero (0). - Norm Compliance Auditing: AI natural language processing was utilized as a logical pre-validator to ensure that
whileloop structures and line returns did not indirectly violate the syntactic restrictions imposed by the school's linter. - Technical Documentation Optimization: AI assistance was employed for the translation and advanced Markdown formatting of this
README.mdfile, ensuring appropriate software engineering terminology in the algorithm justification section.