Error Detection
Push Swap validates all input before attempting to sort. Invalid input triggers an error message and immediate program termination. All error handling is implemented inft_error_exit.c and ft_fill_stack.c.
Error Output
When any error is detected, the program:- Frees all allocated memory (stacks and split arrays)
- Writes
"Error\n"to standard output - Exits with status code
1
ft_error_exit.c:45-52:
Syntax Errors
Theerror_syntax() function validates number format in ft_error_exit.c:54-70.
Invalid Number Format
Numbers must be valid integers with optional leading+ or -:
Invalid Inputs
Validation Rules
Fromft_error_exit.c:54-70, a string is invalid if:
- First character is not
+,-, or a digit (0-9) - Sign without digit: A
+or-is not followed by a digit - Non-digit characters: Any character after the first is not a digit (0-9)
Range Errors
Numbers must fit within theINT_MIN to INT_MAX range (-2147483648 to 2147483647).
From ft_fill_stack.c:87-88:
Examples of Range Errors
Valid Edge Cases
The program uses
long internally in ft_atoi() (ft_fill_stack.c:50-74) to detect overflow before casting to int.Duplicate Detection
Theerror_repetition() function prevents duplicate numbers in ft_error_exit.c:72-83.
Duplicate Numbers
How Duplication is Checked
Fromft_error_exit.c:72-83, for each new number:
- The function traverses the existing stack
- Compares the new number against each existing node
- Returns
1(error) if a match is found - Returns
0(success) if no duplicates exist
Memory Management
Push Swap guarantees proper cleanup even when errors occur.Memory Cleanup Path
Whenfree_errors() is called:
Free split array (if applicable)
If the input was a single string argument (flag == 1),
free_split() releases the array created by ft_split().Free stack nodes
free_stack() traverses the linked list and frees each node in ft_error_exit.c:16-31.Free Stack Implementation
Fromft_error_exit.c:16-31:
Error Detection Flow
The validation happens inft_fill_stack() from ft_fill_stack.c:76-94:
Range validation
After converting to
long with ft_atoi(), the value is checked against INT_MIN and INT_MAX.Testing Error Handling
Validate your implementation handles all error cases:Test Script
Common Error Scenarios
Scenario 1: Mixed Valid and Invalid
Scenario 2: Duplicate After Many Valid
Scenario 3: Overflow Detection
Exit Codes
| Exit Code | Meaning |
|---|---|
0 | Success: sorted or no input |
1 | Error: invalid input detected |
Next Steps
- Review Basic Usage for correct input formats
- See Usage Examples for valid test cases
- Learn about Data Structures internals