In Solidity, variables declared in memory are temporary and are used for storing data that only needs to exist during the execution of a function. Once the function execution is complete, all data stored in memory is cleared and cannot be accessed afterward.

Characteristics of Memory Variables

  • Temporary Storage: Variables in memory are ephemeral. They are created when a function is called and destroyed when the function execution ends.
  • Gas Efficiency: Using memory is generally cheaper than using storage, making it suitable for temporary calculations or data manipulations.
  • Scope: Memory variables are only accessible within the function where they are declared.

Example of Memory Variables

Below is a sample code demonstrating how memory variables work and what happens to them after a function call:


// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract MemoryExample {
// Function to demonstrate memory variable usage
function createMemoryArray(uint256 length) public pure returns (uint256[] memory) {
// Creating a dynamic array in memory
uint256[] memory memoryArray = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
memoryArray[i] = i + 1; // Filling the memory array with values
}
return memoryArray; // Returning the memory array
}

// Function to show that memory data is lost after function execution
function getMemoryArrayLength(uint256 length) public pure returns (uint256) {
uint256[] memory tempArray = new uint256[](length);
// Filling the temporary memory array
for (uint256 i = 0; i < length; i++) {
tempArray[i] = i + 1;
}
// The tempArray is only accessible within this function
return tempArray.length; // Returns the length of the memory array
}
}

What Happens After the Function Call?

In the example above:

  • When you call createMemoryArray, a new memory array is created and filled with values. This array exists only for the duration of the function call.
  • Once the function execution is complete, the memory array is destroyed, and its data is lost. Any attempt to access this array after the function call will result in an error.
  • Similarly, the tempArray in the getMemoryArrayLength function is also temporary and will be cleared after the function execution ends.

Conclusion

In summary, variables declared in memory in Solidity are temporary and exist only during the execution of a function. Once the function call is completed, all data stored in memory is cleared, making it inaccessible afterward. This behavior is essential for managing temporary data efficiently and minimizing gas costs in smart contracts.