UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

Chapter 6.  System call for memory management in C

When writing a program it is assumed that the variables used are stored in memory and available to be used. In principle, the details about how to store and organize the data in memory is not needed for the programmer. However, because the C programming language offers a vision of the memory very close to the RAM, it is a good idea to know more details about how a program memory is organized.

6.1.  The different memory types in a C program

A C program stores all its memory data in three different areas:

  1. Global Memory. This is the area in which the variables that have been declared global or static and those string constants (for example "My string") are stored. In other words, in this memory area you find all those data that are present from the very beginning of a program until the end of the execution.

  2. The stack. It is an area in which the variables appear and disappear at a certain point during the execution of a program. It is used mainly to store the variables local to a function. These variables have a reduced scope, they are only available while the function where they have been defined is being executed. All these variables are stored in the stack and therefore, the area continuously receives operations to insert and delete variables.

  3. The Heap. This area contains memory available to be reserved and freed at any point during the execution of a program. It is not reserved for local variable functions as in the stack, but for memory known as dynamic for data structures that are not known to be needed or even their size until the program is being executed.

It should be noted that out of these three memory zones, only the global memory has a fixed size that is known when the program starts execution. Both the stack and the heap store data the size of which cannot be know until the program is executing. The following figure shows these three memory areas.

The operating system reserves an initial space for heap and stack because of their variables size. Both zones increase and decrease their size within the limits of this maximum space.

Answer the following questions to see if you understood what the content of this document:

  1. A static variable is stored in

    • Global memory

    • Stack memory

    • The heap

  2. A parameter that is passed to a function is stored in

    • Global memory

    • Stack memory

    • The heap

  3. A local variable is stored in

    • Global memory

    • Stack memory

    • The heap