Introduction to Programming Languages/Types of Storage

Introduction edit

The memory in a computer is organized in a hierarchical way. The lowest level memory unit is a register, followed by the cache memory, then the RAM, hard driver, and so on. This organization of the computer's memory is specially useful because most programs need more memory than they are supposed to use.

Program variables are the link between abstractions represented by a program and the computer physical memory units. For instance, in C, you can use the keyword `register` to give the compiler a hint that a variable will be frequently used.

There are also other ways to specify where a variable should be stored. In dynamic typed languages (such as PHP, Javascript, or Python), the programmer cannot tell where a variable should be stored; the interpreter makes that decision. In statically typed languages (such as C and C++), on the other hand, the programmer can tell, based on the type of a variable, where the compiler should store each variable.

The compiler (or the Operating System, for that matter) can put variables in one of three places whithin the program's memory: static memory, stack, or heap. The following sections will cover with more details these three types of memory.


Types of Storage edit

We will use the program below to illustrate several concepts throughout this section. Let us take a look at it.

    int global_var = 7;
    const int global_const = 9;
    const int global_const2 = std::rand();

    void foo() {
      int auto_var = 9;
      int auto_const = 9;
      const int auto_const2 = std::rand();
      static int static_var_u;
      static int static_var = 7;
      static const int static_const = 9;
      static const int static_const2 = std::rand();
      int* ptr = new int(100);
    }

Roughly, the program above declares several types of variables. It serves to illustrate the three kinds of storage we will be discussing in this section. But, first, let us recap what happens when the Operating System loads a program into memory.

When a program is loaded into memory, it is organized into different segments. We show these segments below.


 
The division of a program into segments when it's loaded to memory.

From the figure above we can point out a couple of things. First, the program's instructions (the code itself) goes into the text section. The data and bss sections correspond to the static memory. The heap and the stack are the other memory regions program variables can go into.