Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Incorrect String Length Update in toString(int256) for Negative N… #428

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

mdqst
Copy link

@mdqst mdqst commented Nov 26, 2024

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:

  • Ran forge snapshot?
  • Ran npm run lint?
  • Ran forge test?

…umbers in LibString.sol

Resolved an issue in the toString(int256) function where the string length was updated at an incorrect memory location due to a pointer shift. This fix ensures proper handling of negative numbers and prevents potential memory corruption.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant