0
0
Blockchain / Solidityprogramming~5 mins

Memory allocation in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Memory allocation is how a program sets aside space to store data while it runs. It helps the program remember information it needs to use or change.

When you need to store user data temporarily during a transaction.
When you want to keep track of balances or states in a smart contract.
When you need to create variables that hold values during contract execution.
When managing resources efficiently to avoid running out of memory.
When you want to optimize how your blockchain program uses storage.
Syntax
Blockchain / Solidity
In blockchain smart contracts (like Solidity), memory allocation is often implicit, but you can specify data location:

function example() public {
    uint[] memory tempArray = new uint[](5); // allocate memory for 5 uints
}

Memory in blockchain smart contracts is temporary and cleared after function execution.

Storage is permanent and costs more gas; memory is cheaper but temporary.

Examples
This creates a temporary array of 3 unsigned integers in memory.
Blockchain / Solidity
uint[] memory numbers = new uint[](3);
This stores the string "Alice" temporarily in memory during function execution.
Blockchain / Solidity
string memory name = "Alice";
This mapping is stored permanently in contract storage, not memory.
Blockchain / Solidity
mapping(address => uint) balances; // stored permanently in storage
Sample Program

This smart contract function creates a temporary array in memory, fills it with numbers, and returns it. The array only exists while the function runs.

Blockchain / Solidity
pragma solidity ^0.8.0;

contract MemoryExample {
    function createArray() public pure returns (uint[] memory) {
        uint[] memory tempArray = new uint[](3);
        tempArray[0] = 10;
        tempArray[1] = 20;
        tempArray[2] = 30;
        return tempArray;
    }
}
OutputSuccess
Important Notes

Memory is cleared after the function finishes, so data stored there is temporary.

Use memory for temporary variables and storage for data you want to keep.

Allocating too much memory can increase gas costs, so be efficient.

Summary

Memory allocation sets aside space to hold data temporarily during contract execution.

Memory is cheaper but temporary; storage is permanent but costs more.

Use memory for temporary data like function variables and arrays.