Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solidity: memory vs stack

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?

like image 888
ccfisdog Avatar asked Oct 17 '25 19:10

ccfisdog


1 Answers

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

like image 183
Yilmaz Avatar answered Oct 19 '25 12:10

Yilmaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!