Luke Bourne
Luke Bourne

Reputation: 295

Find which heap an address belongs to?

I'm creating a memory management system and i need a way to find in which heap an allocation I make is. for example i use HeapAlloc and use the heap returned by GetProcessHeap() as the heap to allocate to I would expect it to allocate to that heap, but appears as though it doesn't.

When I use GetProcessHeaps to run through the heaps i find that the process heap is at something like 0x00670000 and my allocated address is at like 0x0243a385 or something. (in other words nowhere near it) And sometimes it can actually be before it (so like 0x004335ab or something)

So, i'd like to know if there is a way I can reliably get the starting address of the heap (and the end address if at all possible!?) that i made the allocation in.

Upvotes: 1

Views: 600

Answers (1)

Mike Vine
Mike Vine

Reputation: 9837

Your understanding of heaps is wrong. In general, modern heaps do not rely on allocating a large chunk of data and then parcelling it up with each allocation as you assume (although they may use this as one of their strategies). This means there is no well defined 'start' or 'end' of a heap. As an example, by default, with Windows heaps large allocations always go direct to the operating system via VirtualAlloc(...) which means that allocations from one heap may interleave with allocations from another.

If you really need to work out which heap an allocation comes from, there is a way, although its really slow so you shouldn't rely on it except for debugging or logging or similar. For actual, normal, code you should really know where allocations came from either via deduced context or by actually storing it.

Warnings aside, you can use HeapWalk to enumerate all allocations from each heap looking for the one you want.

Upvotes: 2

Related Questions