Skip to content
AlisonCameloPublic

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

7 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

This project has been created as part of the 42 curriculum by acamelo.

Piscine C 03 🚀


Description

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.


Instructions

Compilation Requirements and Environment

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

Execution Process and Unit Testing

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:

  1. Navigate to the desired exercise directory:
cd ex00/
  1. Create or add your test file (main.c): Ensure your main.c includes calls to both your function (e.g., ft_strcmp) and the original one (strcmp) to contrast that return values and memory impacts are identical.
  2. Compile the executable binary:
gcc -Wall -Wextra -Werror ft_strcmp.c main.c -o test_executable
  1. Execute the test program:
./test_executable
  1. Memory leak and access verification (Optional but recommended):
valgrind --leak-check=full ./test_executable

Algorithm Explanation and Justification

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:

1. Axiomatic Comparison Algorithms (ft_strcmp and ft_strncmp)

  • Mechanics: Both functions implement a synchronous scan. A single iterator advances in parallel over the memory arrays of s1 and s2. The while loop 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 parameter unsigned int n adds a third restrictive condition. The algorithm is designed with an upper bound of i < n - 1 within 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 where n is greater than the actual length of the strings.
  • Return Value: Instead of returning arbitrary values (such as -1 or 1), 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.

2. Coupling and Displacement Algorithms (ft_strcat and ft_strncat)

  • 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) of dest. The second phase initiates a cloning loop where each character from src is 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. In ft_strncat, the restrictive variable nb is introduced. The algorithm is justified by ensuring strict copy control using the condition j < 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.

3. Text Pattern Localization Algorithm (ft_strstr)

  • Mechanics: To find the sub-string to_find within the base text str, a Naive String Search (Brute Force) approach was selected. The algorithm uses an external main pointer that traverses str. If the current character str[i] matches the beginning of the pattern to_find[0], a secondary counter j is 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.

Resources

Classic References and Documentation

  • 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.

Artificial Intelligence Deployment Statement

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 the n or nb parameter equals zero (0).
  • Norm Compliance Auditing: AI natural language processing was utilized as a logical pre-validator to ensure that while loop 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.md file, ensuring appropriate software engineering terminology in the algorithm justification section.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages