开发者

split malloc mem space

I am using MS VS 2010, C++, unmanaged. I would like to split allocated area if possible. For example let's say I allocated a 1KB space in memory:

void* space = malloc(1024);

later, I decided to have this block as seperate 512B and 512B spaces:

space1 = 512B and space2 = 512B

and finally wh开发者_JS百科en I want to get rid of these spaces I wanna free them seperately:

free(space1);
free(space2);

is this possible without reallocation/expanding/shrinking memory?

Thank you all..


No, you can't free them separately, as malloc() will keep only one copy of the necessary bookkeeping data, so it can only free one chunk. You would have to write your own malloc/free wrappers.


In short: You'll have to write your own memory allocator on top of malloc/new.

The longer version: Since memory allocator implementations differ, there's no way to portably modify their internal data structures that keep track of allocated and free blocks & their boundaries.

For example, there are techniques that prepend a short amount of data to each memory block. You couldn't split such a block because the additional bookkeeping data would expand the size of the block.

Other techniques place their management data externally from the blocks, such as by bitmaps, linked lists and so on. You may have more luck with them.

Again, you'll be better of to write your own allocator.

Even better, if at all possible, try to find alternative means to manage your memory. Maybe pool allocators are more something you need.


You can use Windows APIs for heaps: http://msdn.microsoft.com/en-us/library/aa366711(VS.85).aspx

HeapAlloc() is the equivalent of malloc. The main difference is that is receives another parameter: which heap to use. These heaps can be created with HeapCreate, and you can reserve space for them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜