0

I have a memory pool which is a set size and is split into segments of a given size. When I delete some data it flags the segments that data was using as free. Next time I try to allocate memory but don't have space, I realign the memory by shifting all the data down (e.g. First 2 segments are cleared, move all data down by 2 blocks). This all works fine but my issue is my pointers to that data don't change and I am not sure how I can go about doing this.

I allocate memory from my pool by returning a void* to the space in memory, lets assume my pool is the size to hold 2*sizeof(Data).

Data* poolTest = new(pool->GetMemory(sizeof(Data))) Data(5, 5, 5);

So the pool has no reference to the pointer poolTest.

So now if I do this:

pool->Free(poolTest);
Data* poolTest2 = new(pool->GetMemory(sizeof(Data))) Data(4, 5, 5);
Data* poolTest3 = new(pool->GetMemory(sizeof(Data))) Data(3, 5, 5);

The creation of poolTest3 triggers a realignment of memory and now poolTest2 points to the same address as poolTest3 and poolTest1 points to the address that poolTest2 should point to.

I might just be missing something, or my structure is screwed up but I am really stuck on this.

4

1 回答 1

2

改写你的问题:

我想在内存中移动数据以为新分配腾出空间。如何确保现有指针仍指向正确的位置?

你不能,除非你跟踪所有的指针,比如说,通过使用一个数组,而不是像这样访问你的数据:

*direct_ptr

你现在必须这样做:

*ptr_map[indirect_ptr]

每次移动东西时,都需要相应地修改 ptr_map。

数组的行为应该像一个堆栈。您可能会编写一个指针包装类,它在构造函数中增加一些全局/静态索引并在析构函数中减少它。

它可能会节省一点空间,但对计算机来说效率很低,对程序员来说也很混乱。

如果您想做自己的内存管理,请务必签出:

https://en.wikipedia.org/wiki/Buddy_memory_allocation

https://en.wikipedia.org/wiki/Slab_allocation

以及对现有技术的一个很好的概述:

http://pages.cs.wisc.edu/~remzi/OSTEP/vm-freespace.pdf

于 2018-11-08T03:42:26.917 回答