Explain how memory is allocated to the program at run time.

  • When a variable is defined in the source program, the type of the variable determines how much memory the compiler allocates.
  • When the program executes, the variable consumes this amount of memory regardless of whether the program actually uses the memory allocated. This is particularly true for arrays.
  • However, in many situations, it is not clear how much memory the program will actually need. For example, we may have declared arrays to be large enough to hold the maximum number of elements we expect our application to handle.
  • If too much memory is allocated and then not used, there is a waste of memory. If not enough memory is allocated, the program is not able to fully handle the input data.
  • We can make our program more flexible if, during execution, it could allocate initial and additional memory when needed and free up the memory when it is no more needed.
  • Allocation of memory during execution is called dynamic memory allocation. C provides library functions to allocate and free up memory dynamically during program execution. Dynamic memory is allocated on the heap by the system.
  • It is important to realize that dynamic memory allocation also has limits. If memory is repeatedly allocated, eventually the system will run out of memory.

Leave a Reply