0
votes

In C, for example, the heap is managed by malloc(), free(), and friends. The heap manager generally works by keeping a list of free blocks in the heap with a linked list . Each free block of memory in the heap can contain a header with information about how much free memory it contains and a pointer to the next free block of memory...this all makes sense in terms of the linked-list implementation of a heap manager.

My question is, the linked list data structure requires a head pointer, pointing to the first free memory block in the heap. In the context of glibc, for example, Where is the this pointer stored? Is it in the heap or stack? Its persistence suggest that it would be in the heap, but I don't see it explicitly mentioned anywhere.

1
I think there is no definitive answer to that, as the implementations vary across systems and architectures. The source code of the glibc, uclibc, etc. is free, you could take a look there and see how they solve that. - Pablo
None of this is explicitly mentioned anywhere. It's the only sane way to do it, but it isn't the only way, and how to do it isn't mandated anywhere. - user207421
Having a heap base pointer in the heap sounds a bit too incestuous to me. Can't be on 'the stack' since there may be many stacks. In most cases, it's gonna be a static in the crt lib. - Martin James

1 Answers

1
votes

Looking through glibc's implementation of malloc, and as outlined in this post, the header-information (malloc_state) for the main arena (heap region created by main()) is a static variable kept in libc.so's data segment. The header-information includes information such as top-chunk, last free-chunk, etc, where chunks are analogous to linked-list nodes.