Where does computer store used and unused memory address to access it ?Are base address and length or ending address stored side by side?
There are many possible data structures that can be used, but a very basic one is using a free list.
We divide memory in blocks. Each block starts with two words, one being a pointer, the other one being the block length. Then we organize such blocks in a linked list, called the "free list".
When memory is allocated (
malloc(s)), we scan the free list until a large enough block is found. We remove it from the list, and return a pointer to the start to the block, plus two words.
When memory is freed (
free(p)), we decrement
p by two words, and prepend the block to the free list.
Further options: we can sometimes split / merge blocks. E.g. when
malloc(s) finds a block which is much larger than
s, it can split the block in two, and return the first part (say, of length
s), only. This increases the number of the blocks. Similarly,
free can check the free list to spot if there are adjacent blocks, and merge them into one. More advanced data structures can be used to make this operation efficient.
In the real world, the problem is more complex since the memory is handled by the OS, which grants it to processes, and then (usually) by the runtime support of the programming language, which implements something like
malloc,free by further subdividing the OS-granted memory.