Skip to content

Instantly share code, notes, and snippets.

@hodzanassredin
Created November 21, 2011 10:19
Show Gist options
  • Select an option

  • Save hodzanassredin/1382234 to your computer and use it in GitHub Desktop.

Select an option

Save hodzanassredin/1382234 to your computer and use it in GitHub Desktop.
custom linear memory allocator
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace Allocators
{
class Program
{
static unsafe void Main(string[] args)
{
LinearAllocator alloc = new LinearAllocator();
Test* ptr = (Test*)alloc.Allocate(sizeof(Test));
(*ptr).id = 0;
(*ptr).age = 33;
var name = "test".ToArray();
for (int i = 0; i < name.Length; i++)
{
(*ptr).name[i] = name[i];
}
alloc.DeallocateAll();
Test* ptr2 = (Test*)alloc.Allocate(sizeof(Test));
for (int i = 0; i < 4; i++)
{
Console.Write((*ptr2).name[i]);
}
alloc.DeallocateAll();
alloc.Clear();
Test* ptr3 = (Test*)alloc.Allocate(sizeof(Test));
for (int i = 0; i < 4; i++)
{
Console.Write((*ptr3).name[i]);
}
Console.ReadKey();
}
}
unsafe struct Test
{
public int id;
public fixed char name[20];
public int age;
}
unsafe struct LinearAllocator
{
const int max_size = 1000000;
fixed byte buffer[max_size];
long _offset;
public byte* Allocate(long size)
{
var newOffset = _offset + size;
if (newOffset < max_size)
{
fixed (byte* ptr = buffer)
{
byte* res = ptr + _offset;
_offset = newOffset;
return res;
}
}
return null;
}
public void DeallocateAll()
{
_offset = 0;
}
public void Clear()
{
fixed (byte* ptr = buffer)
{
for (int i = 0; i < max_size; i++)
{
ptr[i] = 0;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment