Fix Incorrect String Length Update in toString(int256) for Negative N…
Description
The code contains an issue in the handling of negative numbers within the toString(int256 value) function, specifically related to updating the string length in memory.
Issue
The problem lies in this line:
mstore(str, add(length, 1)) // Update the string length.
In the above snippet, the string length is updated at the position of str. However, the pointer str was already shifted by 1 byte earlier:
str := sub(str, 1) // Move back the string pointer by a byte.
As a result, the length is written to an incorrect memory location (1 byte earlier), potentially causing data corruption.
Fix
To resolve this, the string length should be written to the original pointer position before shifting str. The corrected code is:
let originalStr := str // Save the original pointer before shifting.
str := sub(str, 1) // Move back the string pointer by a byte.
mstore(originalStr, add(length, 1)) // Update the string length at the original pointer.
This ensures that the string length is properly updated in memory without overwriting or misplacing data.
Importance of the Fix
This bug might not immediately surface during testing, as the toString function works correctly for positive numbers. However, when handling negative numbers, the issue can lead to corrupted memory and unintended behavior, especially in contracts that rely on precise string manipulations. Fixing this ensures robustness and consistency in handling both positive and negative numbers.
Checklist
Ensure you completed all of the steps below before submitting your pull request:
- [x] Ran
forge snapshot? - [x] Ran
npm run lint? - [x] Ran
forge test?