3

In this example I only modify string a, but both a and b are changed. It seems like the string wasn't copied. I only want to change a. How do you copy a string and how do you pass a string by value to another function?

function test() public view returns (string memory, string memory)
{
    string memory a = "Hello?";
    string memory b = a;
    bytes(a)[5] = '!'; // modify string a
    return (a, b);
}
3

Strings and arrays in solidity are never passed by value. The type string memory means that the variable contains a memory pointer, so when you assign a = b you are only copying the pointer to the string, not the string itself. Therefore, there is only ever one string.

If you want a copy, you will have to manually make a copy.

This function can copy a bytes memory, but you can easily cast back and forth between string memory and bytes memory.

function copyBytes(bytes memory _bytes) private pure returns (bytes memory)
{
    bytes memory copy = new bytes(_bytes.length);
    uint256 max = _bytes.length + 31;
    for (uint256 i=32; i<=max; i+=32)
    {
        assembly { mstore(add(copy, i), mload(add(_bytes, i))) }
    }
    return copy;
}

Using copyBytes in your function would look like:

function test() public view returns (string memory, string memory)
{
    string memory a = "Hello?";
    string memory b = string(copyBytes(bytes(a)));
    bytes(a)[5] = '!'; // modify string a
    return (a, b);
}

This will return ("Hello!", "Hello?")

1
  • 1
    Thanks!! works great
    – Skellomag
    Dec 22 '20 at 10:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.