Reputation: 81
I read the code of memory management, and I can't understand the meaning of the following function, could you please tell how does the function work?
// Get the reference of next block's address in current block.
static void*& GetNextBlock(void* p_block)
{
return *(reinterpret_cast<void**>(p_block));
}
According to the comment upon the code, the function returns the address of p_block's next block, but I think the function returns the address of p_block.
Upvotes: 2
Views: 403
Reputation: 881563
The p_block
variable is an address of some piece of memory. You cast that to a void**
with reinterpret_cast<void**>(p_block)
, meaning it's now considered the address (A) of an address (B) in memory. Then you dereference that (with *something
) to get the address B
.
This scheme is often used in memory arenas where a memory block (usually a control segment before the memory addresses returned from malloc
) contains the address of the next block (whether allocated or not). For example:
+----------+ +----------+
firstFree -> | nextFree | -> | nextFree | -> nullptr
+----------+ +----------+
| user bit | | user bit |
+----------+ +----------+
Upvotes: 4