Hello,
Today I decided that I want to gain some knowledge about memory management.
I don't know much about memory management so i thought it would be a nice "exercise" to try to create a pool allocator.
Actually everything is working as expected but I think I did something wrong.
Here's the code :
PoolAllocator.h
[source]
#pragma once
class PoolAllocator
{
public:
PoolAllocator(void);
~PoolAllocator(void);
void allocate(const size_t amount);
char *obtain(const size_t amount);
void free(void *mem);
private:
char *memory;
char *at;
int atAmount;
int size;
};
[/source]
PoolAllocator.cpp
[source]
#include "PoolAllocator.h"
PoolAllocator::PoolAllocator(void)
{
}
PoolAllocator::~PoolAllocator(void)
{
delete[] memory;
delete[] at;
}
void PoolAllocator::allocate(const size_t maxSize)
{
memory = new char[maxSize];
at = &memory[0];
atAmount = 0;
size = maxSize;
}
char *PoolAllocator::obtain(const size_t amount)
{
if(atAmount + amount > size - 1)
return nullptr;
at += amount;
return at;
}
void PoolAllocator::free(void *mem)
{
}
[/source]
main.cpp
[source]
#include <Windows.h>
#include <iostream>
#include "PoolAllocator.h"
class A
{
public:
int val;
};
class B
{
public:
int val;
};
int main()
{
PoolAllocator allocator;
allocator.allocate(1000);
A *a = (A*)allocator.obtain(sizeof(A));
a->val = 10;
std::cout << "A : " << a->val << std::endl;
B *b = (B*)allocator.obtain(sizeof(B));
b->val = 20;
std::cout << "A : " << a->val << std::endl << "B : " << b->val << std::endl;
system("pause");
return 0;
}
[/source]
My knowledge in memory management is really limited, so it could be that I made some 'horrible' mistake or something.
Basically I just want someone to check this code.
Thanks in advance !