0

I have a simple question about solidity memory declaration: It both return bytes data in following two cases, but one needs to have memory keyword and another does not. I am a bit confused about the theory behind the scene. It will be appreciated anybody can help to clarify it.

function toBytes(string memory data) pure external returns(bytes memory) {
    return bytes(data);
}
function keccakBytes(string memory data) pure external returns(bytes32) {
    return keccak256(bytes(data));
}
0

The difference is that the first function returns bytes, and the second one returns bytes32, the difference being that the former can have an arbitrary length, while the latter is limited to 32 bytes.

The bytes32 will fit in a single item on the stack, but bytes can have a length greater than 32 bytes. Since the number and length of items on the stack is limited, this means that bytes need to be written to memory. The stack is also cheaper to use (in terms of gas), so that's why bytes32 uses the stack instead of memory.

You can read more about the stack, memory (and storage) in the Solidity documentation here.

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.