C++ Memory Map

« Previous Tutorial Next Tutorial »

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.

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 :

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 :

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 »

© Copyright 2021. All Rights Reserved.