Search code examples
cdynamic-memory-allocation

How does dynamic memory allocation work?


Consider the following code:

int *p = malloc(4);
int *i = malloc(4);

Now, a chunk of memory (4 bytes in the above situation) has been allocated and the base address is stored in p.

While allocating the memory in the line int *i = malloc(4).

How does the compiler come to know that this chunk of memory is allocated?

Why is it not allocating the same chunk of memory that has been allocated with int *p = malloc(4) ?


Solution

  • When you use routines like malloc in your code and and compile and link your code into an executable program, a library of software routines is linked into your code too. The routines in that library have software for requesting memory from the operating system, for dividing that memory into parts and giving it out when requested with malloc, and for keeping track of what has been given out and what has been released with free.

    So, whenever you compile a very small program, you get along with it a large library of additional software that people have worked on for many years.