Consider the following Solidity function that copies an array from storage to memory and modifies it. What will be the value of arr[0] in storage after calling modifyArray()?
pragma solidity ^0.8.0; contract Test { uint[] public arr = [1, 2, 3]; function modifyArray() public { uint[] memory temp = arr; temp[0] = 100; } }
Remember that memory variables are copies and do not affect storage unless explicitly written back.
The temp array is a copy of arr in memory. Modifying temp[0] does not change the original arr in storage. So, arr[0] remains 1.
Which statement correctly describes the difference between stack and heap memory in blockchain smart contracts?
Think about where local variables and dynamic data are stored during execution.
Stack memory holds local variables and function call data, which is fixed size and fast. Heap memory is used for dynamic data like arrays and structs.
What error will the following Solidity code produce when compiled?
pragma solidity ^0.8.0; contract Demo { function test() public pure returns (uint) { uint[] memory arr; arr[0] = 10; return arr[0]; } }
Think about how memory arrays must be declared in Solidity.
Memory arrays must have a fixed length when declared. Declaring uint[] memory arr; without length causes a compilation error.
What will be the gas cost difference when running the following two functions in Solidity?
Function storeData() writes to storage, useMemory() uses memory only.
pragma solidity ^0.8.0; contract GasTest { uint[] public data; function storeData() public { for (uint i = 0; i < 5; i++) { data.push(i); } } function useMemory() public pure returns (uint) { uint[] memory temp = new uint[](5); for (uint i = 0; i < 5; i++) { temp[i] = i; } return temp[4]; } }
Recall that writing to blockchain storage is more costly than using temporary memory.
Writing to storage consumes much more gas than using memory because storage changes are permanent and stored on-chain. Memory is temporary and cheaper.
How can improper memory allocation contribute to a reentrancy attack vulnerability in a smart contract?
Memory is temporary and isolated per execution context in smart contracts.
Memory allocation has no impact on reentrancy since it is only temporary and isolated per call.