Skip to main content
The allocator example demonstrates how to utilize the allocator feature when writing a contract. Open in Codespaces Open in Codeanywhere The soroban-sdk crate provides a lightweight bump-pointer allocator which can be used to emulate heap memory allocation in a Wasm smart contract.

Run the Example

First go through the Setup process to get your development environment configured, then clone the v23.0.0 tag of soroban-examples repository:
Or, skip the development environment setup and open this example in GitHub Codespaces or Code Anywhere. To run the tests for the example, navigate to the alloc directory, and use cargo test.
You should see the output:

Dependencies

This example depends on the alloc feature in soroban-sdk. To include it, add “alloc” to the “features” list of soroban-sdk in the Cargo.toml file:
alloc/Cargo.toml

Code

alloc/src/lib.rs
Ref: https://github.com/stellar/soroban-examples/tree/v23.0.0/alloc

How it Works

Imports the alloc crate, which is required in order to support allocation under no_std. See Contract Rust dialect for more info about no_std.
Creates a contiguous growable array v1 with contents allocated on the heap memory.
The heap memory in the context of a smart contract actually refers to the Wasm linear memory. The alloc will use the global allocator provided by the soroban sdk to interact with the linear memory.
Using heap allocated array is typically slow and computationally expensive. Try to avoid it and instead use a fixed-sized array or soroban_sdk::vec! whenever possible.This is especially the case for a large-size array. Whenever the array size grows beyond the current linear memory size, which is multiple of the page size (64KB), the wasm32::memory_grow is invoked to grow the linear memory by more pages as necessary, which is very computationally expensive.
The remaining code pushes values (0..count) to v1, then computes and returns their sum. This is the simplest example to illustrate how to use the allocator.