Advanced C Course – Class 3

Dynamic memory

In C we can reserve memory dynamically at runtime.

In practice there are two types of memory: static memory managed by the compiler and dynamic memory managed by the programmer.

When variables are defined, the compiler assigns them the necessary space depending on the type of the variable.

Depending on the scope where the variable is defined, the compiler allocates memory on the stack for local variables and function parameters.

For global variables the compiler allocates the memory of the variables in a data segment separately.

The programmer can dynamically reserve memory at runtime with the malloc function, which passes the number of bytes of memory to reserve.

Reserved memory is created in a data segment called HEAP used only for dynamic memory.

The malloc function returns a pointer to the reserved memory area.

E.g.

int * p = (int *) malloc (200);

The malloc function reserves 200 bytes of memory and returns an untyped pointer to the reserved area.

An explicit casting is done to indicate that there are integers in the memory area.

The pointer p points to the reserved area with malloc.

Dynamic memory allocation will allow us to manage amounts of data at the time the program is run and not at the time of compilation.

In the example above if the size of an integer is 2 bytes, memory will be reserved for 100 integers.

The previous case can also be defined in the form

int * p = (int *) malloc (100 * sizeof (int));

It should be noted that the memory reserved with malloc is controlled by the programmer, not the compiler, and it is he who must free it when he does not use it.

The free function must be used to free up dynamically allocated memory.

E.g

free (p);

 

Leave a Reply

Your email address will not be published. Required fields are marked *