Can someone explain me what this code does?

Jun 3, 2016 at 8:46pm
closed account (1vD3vCM9)
Hey everyone, I want to overload the operator new and delete and so far it all works.
I found a C++ Game Engine that, however, uses an different technique than mine..
I don't know what is different, the results are the same, I can't seem to understand what he did there.

(my code)
1
2
3
4
5
6
7
8
9
10
void* MemoryManager::Allocate(size_t size) {
_memInfo._MemoryAllocated += size;
_memInfo._NumAllocations++;
void* storage = (size_t*)malloc(size);
if (storage != nullptr) return storage;
}

void MemoryManager::Free(void* ptr) {
free(ptr);
}


His Code (The Sparky Engine's Code)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#define SP_ALIGNMENT_VALUE 16
#define SP_ALLOC(size) _aligned_malloc(size, SP_ALIGNMENT_VALUE )
#define SP_FREE(ptr) _aligned_free(ptr)

void* MemoryManager::Allocate(size_t size) {
		size_t actualSize = size + sizeof(size_t);
		Byte* result = (Byte*)SP_ALLOC(actualSize);
		memset(result, 0, actualSize);
		memcpy(result, &size, sizeof(size_t));
		result += sizeof(size_t);
		return result;
	}

	void MemoryManager::Free(void* ptr) {
		Byte* memory = ((Byte*)ptr) - sizeof(size_t);
		size_t size = *(size_t*)memory;
		SP_FREE(memory);
	}

I tried to understand what he did there, but I couldn't understand.
Can someone try to explain to me what he does and if I should use it?
Last edited on Jun 3, 2016 at 8:46pm
Jun 3, 2016 at 10:19pm
It allocates requested_bytes + sizeof(size_t) and writes the value of requested_bytes at the start of new_buffer, then returns new_buffer + sizeof(size_t).
So, for example, if you allocate 1024 bytes, you will get this back in memory (assuming 32-bit machine and little endianness):
1
2
3
00 04 00 00 00 00 00 ...
{_________} ^ The pointer you get back points here.
     `-> Invisible data.
Topic archived. No new replies allowed.