DevShiftTeam / AppShift-MemoryPool

A very fast cross-platform memory pool mechanism for C++ built using a data-oriented approach (3 to 24 times faster than regular new or delete, depending on operating system & compiler)
Apache License 2.0
215 stars 25 forks source link

Crash when doing repeated interleaved allocations, reallocations, and frees #9

Closed azureskydiver closed 3 years ago

azureskydiver commented 3 years ago

The following code crashes:

#include <iostream>
#include "MemoryPool.h"

int main() {

    const char* str = "Hello ";
    int length = strlen(str);
    const char* add = "World";
    int add_length = strlen(add);

    CPPShift::Memory::MemoryPool* mp = CPPShift::Memory::MemoryPoolManager::create();
    for (int i = 0; i < 1000000; i++) {
        // Alloc
        char * start = new (mp) char[length];

        // Realloc
        char* old = start;
        start = new (mp) char[length + add_length];
        CPPShift::Memory::MemoryPoolManager::free(old);

        // Free
        CPPShift::Memory::MemoryPoolManager::free(start);
    }

    return 0;
}
LessComplexity commented 3 years ago

Hi the problem was that the first block was empty and it tried to access it the same way as not a first block when freeing which made it access the undefined memory of the prev pointer that didn't exist. Thank you :)