Why does mstore(c, p) not copy p to c?

function test()returns (bytes32) {
    bytes32 c;
    bytes32 p = 0xFF;
    assembly {
        mstore(c, p)
    return c;

The confusion here is probably because unlike traditional processors, EVM has several different “memories” accessed via different opcodes:

  1. General memory accessed via MSTORE, MLOAD, MSTORE8, and MLOAD8. It is used to store non atomic data structures such as strings, arrays, and structs.
  2. Stack memory accessed via PUSH*, DUP*, SWAP*, POP. It is used for local variables and parameters and return values of internally called methods.
  3. Call data memory accessed via CALLDATALOAD, CALLDATASIZE, and CALLDATACOPY. This memory is read-only and used for parameters of externally called methods.
  4. Return data memory accessed via RETURNDATASIZE, RETURNDATACOPY. This memory is also read-only and is used for values returned by externally called methods.
  5. Code memory accessed via CODESIZE and CODECOPY. Also read-only and contains byte code of the current smart contract. This memory may also be used for deployment time constants though this feature is not yet implemented in Solidity.

Having such many memories makes it difficult to create compilers from C-like languages into EVM, because in C-like languages the same pointer may refer to any variable, either local, or dynamic, or constant resource.

In your example c is a local variable allocated in stack and thus it cannot be accessed via MSTORE. The code you wrote treats value of c as an address in general memory and copies value of b into memory slot at this address.

| improve this answer | |

enter image description here

The mstore instruction "Save a word to memory". Essentially, it stores at address mu_s[0] (the value of c) of the memory the value of the variable p. So with your assembly instruction, you are storing at address 0 of memory the value 0xff.

The problem is that c is not stored in memory (and in particular not at this address), but rather it is stored in Stack (according to this link).

So to copy the value of p in c, you have to write this assembly code (I know it is less cool, but it works):

 assembly {
    c := p
| improve this answer | |

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.