C++ Memory Map

Since pointers have a close relation with memory as they store address of a memory location and also they facilitate the dynamic memory allocation routines of C++, we must understand the way C++ organizes memory for its programs. After compiling a program, C++ creates four logically distinct regions of memory that are used for four distinct specific functions.

  • One region in the memory holds the compiled code of the program. Every instructions and every function of the program starts at a particular address.
  • The next region is the memory area where the global variables of the program are stored. Global variables remain in the memory as long as program continues.
  • The third region is known as Stack, is used for great many things while your program executes. The stack is used for holding the return address at function calls, arguments passed to the functions, and local variables for functions. The local variables remain in memory as long as the function continues and after that they are erased from the memory. The stack also stores the current state of the CPU.
  • The Heap memory area is a region of free memory from which chunks of memory are allocated via C++'s dynamic memory allocation functions.

Dynamic and Static Allocation of Memory in C++

The golden rule of computers states that anything and everything (date or instruction) that needs to be processed must be loaded into internal memory before its processing takes place. Therefore, every data and instruction that is being executed must be allocated some area in the main(internal) memory. The main(internal) memory is allocated in these two ways :

  • Statically
  • Dynamically

Static Memory Allocation in C++

When the amount of memory to be allocated is known beforehand and the memory is allocated during compilation itself, it is referred to as static memory allocation. For example, when you declare a variable as follows :

short avar ;

then, in such a case the computer knows that what the length of a short variable is. Generally, it is 2 bytes. So, a chunk of 2 bytes internal memory will be allocated to variable avar during compilation itself. Thus, it is an example of static memory allocation.

Dynamic Memory Allocation in C++

When the amount of memory to be allocated is not known beforehand rather it is required to allocate (main) memory as and when required during runtime (when the program is actually executing) itself, then, the allocation of memory at run time is referred to as dynamic memory allocation.

C++ offers these two operators for dynamic memory allocations :

  • new
  • delete

The operator new allocates the memory dynamically and returns a pointer storing the memory address of the allocated memory. The operator delete deallocates the memory (the reverse of new) pointer by the given pointer.

C++ Online Test

« Previous Tutorial Next Tutorial »

Follow/Like Us on Facebook

Subscribe Us on YouTube