3

Solidity has 3 difference memory storage: storage, memory and stack. After reading lots of articles online, I still can't understand the difference between memory and stack. My question would be:

Q1. What's the difference between memory and stack?

Q2. Suppose I have defined a local variable in function, how do I know that this variable is stored in memory or stack? (The variable is in memory only if the declaration of the variable goes with the "memory" keyword?)

Thanks, everyone.


Thanks for the reply from @Yilmaz . According to your answer, say we have a function written like this:

function test() public {
    string memory str;
    int i;
}

Are str and i both on "memory" and on "stack" simultaneously?

My third question is:

Q3. Why do only array, struct, and mapping types need to specify memory location? Why Solidity doesn't allow me to write int memory i; in above code?

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
ccfisdog
  • 31
  • 3
  • Likely related: [What and where are the stack and heap?](https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap) and [In Ethereum Solidity, what is the purpose of the "memory" keyword?](https://stackoverflow.com/q/33839154/11082165) – Brian61354270 Jul 09 '22 at 14:27

1 Answers1

5

enter image description here

Storage is where the variables are permanently stored on the blockchain. If you want to manipulate the data in storage you copy it to the memory. Then, all memory code is executed on stack. Stack has a maximum depth of 1024 elements and supports the word size of 256 bits.

When you define the local variable it is stored in memory and then pushed to the stack for execution.

  • Stack is a temporary storage that the Ethereum EVM uses to bring data from other storage to work on them. str and i both are not on "memory" and on "stack" simultaneously. You see the image, there is push code that moves the variable from memory to stack. If EVM was keeping both on the memory and stack instantaneously, it would not be cost efficient.

for your 3rd question please refer this: In Ethereum Solidity, what is the purpose of the "memory" keyword?

I explained it with details

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
  • Thanks for your answer, I have make an example in my question, please help me verify wether I get this rigtht. Thank you. – ccfisdog Jul 09 '22 at 16:09
  • When you define the local variable it is stored in memory and then pushed to the stack for execution. when the function gets executed it is executed on stack. so code is pushed to the stack – Yilmaz Jul 09 '22 at 17:02