Heap - How free bytes are tracked?

183 views Asked by At

I am reading about heap and stack usage and I have a question about the heap and the dynamically allocated memory.

How/where the heap memory used by an application is known to be used or availabe?

What I always see in an explanation of dynamic allocation is something like this :

int *p;
p = (int*)malloc(sizeof(int));/* A space in the heap is allocated to store an int*/
p = (int*)malloc(sizeof(int));/* p now points to another space in the heap ; the first allocated space is lost, causing a memory leak*/

I understand the /* comments */ I wrote in the code but I don't clearly understand that the first space is "lost" so I came up with two ideas:

  • everytime there is a dynamic allocation, "something" must keep track of the space reserved in memory (address of the first byte and the size of the space allocated) : something like a list that is updated at each dynamic allocation.
  • or is there some sort of a flag for each byte saying that it is free or used by an application.

In this way, a call to the free function would, for the first idea, update the list by removing the address of the bytes or for the second one change the flags.

Thank you for your time.

0

There are 0 answers