UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

6.5.  Calling the memory management functions

The first observation when looking at the type of data returned by the memory management functions is that using dynamic memory and using pointers go hand by hand. A program may manipulate a portion of dynamic memory because it has the address of the first memory byte, and this address is stored in a data of type pointer. This pointer is used both to access the data stored in that memory portion, and to deallocate this area once is no longer needed (with the free() function).

When the function malloc is invoked it returns the value of a memory address as type void *, that is, a pointer to any data. But this memory address is stored in the program in a pointer of a different data type. In order to avoid warnings when compiling, a prefix is added to the invocation of malloc that is called casting. A casting is an expression written by the programmer notifying the compiler that certain data should be treated as if it were a different data type. For example, the following statement reserves space for a structure of type struct cell_info and the address of that memory location is assigned to the pointer cell_ptr.

#define TABLE_SIZE 10
struct cell_info
{
    int a;
    int b;
    int table[TABLE_SIZE];
};
struct cell_info *cell_ptr;

cell_ptr = (struct cell_info *)malloc(sizeof(struct cell_info));

It should be noted that the exact size for the memory portion to be reserved is obtained with the function sizeof() that given any data type or variable, returns the number of bytes that occupies in memory. The casting (struct cell_info *) makes the assignment over the variable cell_ptr as if the memory address is a pointer of that type, and therefore, correct.

Once the memory portion has been obtained, the memory access is performed normally using the obtained pointer, for example:

cell_ptr->a = 10;
cell_ptr->b = a + 20;
cell_ptr->table[5] = 0;

The rule to call the function malloc can be stated as follows. The space in dynamic memory to store a variable of type T is obtained by

T *ptr = (T *)malloc(sizeof(T));

Once a data structure reserved with dynamic memory is no longer required, it can be released using the free function. In the case of the previous example, the invocation would be

free(cell_ptr)

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

  1. The "malloc" and "calloc" calls return in case that there are not any errors

    • A pointer to the beginning of the allocated memory

    • A pointer to the end of the allocated memory

    • A pointer in the middle of the allocated memory

  2. If p is a pointer to integer, and we execute p=p+1;

    • The value of p increments the size of an integer

    • The value of p increments the size of a pointer