Skip to content

Instantly share code, notes, and snippets.

@juniorUsca
Last active March 16, 2020 21:49
Show Gist options
  • Save juniorUsca/084a74f359a66441297bb2299a1708a6 to your computer and use it in GitHub Desktop.
Save juniorUsca/084a74f359a66441297bb2299a1708a6 to your computer and use it in GitHub Desktop.
php memory allocation
<?php
class MemoryManager {
private $_buffer;
private $_allocation;
private $_numBytes;
private $_currentNumBytes;
function __construct(&$buffer, $numBytes) {
$buffer = array_fill(0, $numBytes, NULL);
$this->_buffer = $buffer;
$this->_numBytes = $numBytes;
$this->_currentNumBytes = 0;
$this->_allocation = array_fill(0, $numBytes, NULL);
}
/**
* return pointer
*/
function &alloc($size) {
if ($this->_currentNumBytes+$size >= $this->_numBytes) {
// throw error
echo "Full memory";
$null_var = NULL;
return $null_var;
}
// search free position
$acc = 0;
$flag = false;
for ($i=0; $i < $this->_numBytes; $i++) {
if (is_null($this->_allocation[$i])) $acc++;
else $acc = 0;
if ($acc >= $size) {
$flag = true;
break;
}
}
// allocate memory
if ($flag) {
$this->_currentNumBytes += $size;
$memoryDirection = $i - ($size-1);
for ($j=0; $j < $size; $j++) {
$this->_allocation[$memoryDirection+$j] = -1;
}
$this->_allocation[$memoryDirection] = $size;
return $memoryDirection;
}
// throw error
echo "Limit error";
$null_var = NULL;
return $null_var;
}
function free($ptr) {
if ($this->_allocation[$ptr] == -1) {
// throw error
echo "Segmentation fault";
return;
}
for ($i=0; $i < $this->_allocation[$ptr]; $i++) {
$this->_buffer[$ptr+$i] = NULL;
}
}
function assign($ptr, $value) {
$this->_buffer[$ptr] = $value;
}
function next(&$ptr) {
return $ptr+1; // move direction memory a block
}
function getValue($ptr) {
return $this->_buffer[$ptr];
}
}
$NewBuffer = NULL;
$New = new MemoryManager($NewBuffer, 25);
$pointer = $New->alloc(3);
$New->assign($pointer, 4); // *pointer = 4
$New->assign($pointer+1, 7); // *(pointer+1) = 7
$New->assign($pointer+2, 2); // *(pointer+2) = 2
echo "The pointer value is: ".$New->getValue($pointer);
echo "\nThe ++pointer value is: ".$New->getValue($pointer+1);
echo "\n";
$New->free($pointer);
echo "The pointer value is: ".(is_null($New->getValue($pointer)) ? 'NULL' : $New->getValue($pointer));
echo "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment