Skip to content

Instantly share code, notes, and snippets.

@cds-amal
Created March 2, 2024 14:19
Show Gist options
  • Save cds-amal/8cc1bdeb4ca9f30b0482866e51eb6ba8 to your computer and use it in GitHub Desktop.
Save cds-amal/8cc1bdeb4ca9f30b0482866e51eb6ba8 to your computer and use it in GitHub Desktop.
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.8.24+commit.e11b9ed9.js&optimize=false&runs=200&gist=
{
"overrides": [
{
"files": "*.sol",
"options": {
"printWidth": 80,
"tabWidth": 4,
"useTabs": false,
"singleQuote": false,
"bracketSpacing": false
}
},
{
"files": "*.yml",
"options": {}
},
{
"files": "*.yaml",
"options": {}
},
{
"files": "*.toml",
"options": {}
},
{
"files": "*.json",
"options": {}
},
{
"files": "*.js",
"options": {}
},
{
"files": "*.ts",
"options": {}
}
]
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.21;
contract MemorySafetyExample {
function unsafeAssembly() public pure returns (uint) {
uint x;
uint y = 1;
assembly {
// Directly manipulate memory in an unsafe manner
x := mload(0x40) // Load from the free memory pointer
mstore(x, y) // Store y at location x
mstore(add(x, 0x20), 2) // Deliberately create a memory safety issue
}
return x;
}
}
contract MemorySafetyTest {
MemorySafetyExample example;
function setUp() public {
example = new MemorySafetyExample();
}
function testIsOne() public view returns (uint x) {
// x should be 1, this call may fail or lead
// to undefined behavior due to memory safety issues
x = example.unsafeAssembly();
}
function assertIsOne() public view {
// x should be 1, this call may fail or lead
// to undefined behavior due to memory safety issues
require(example.unsafeAssembly() == 1, "unexpected");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment