Dynamic memory allocation

Location
  1. Courses

    /

  2. Quick C course

    /

  3. Dynamic memory allocation

We learned earlier that the amount of memory usable by statically allocated arrays, like that:

int array[50];

Is limited.

Let us learn to dynamically allocate them, so the only limit is the amount of free memory the computer has.

Explicit cast

Before continuing, we have to learn to manually convert between variable types. When the conversion is done automatically, we say it is 'implicit':

int var = 6; long var2 = var; // Automatic conversion 'int' -> 'long'.

We can manually (explicitly) convert a variable, like that:

long var2 = (long)var; // Explicit conversion.

The operator sizeof

The operator sizeof returns the size, in bytes, of a type.

Here we print the size of the type 'int':

printf("%d\n", sizeof(int));

It can also be used to retrieve the size, in bytes, of a statically allocated array:

int array[20]; printf("%d == %d * %d.\n", sizeof(array), 20, sizeof(int));

Pointer of type void

A pointer of type void, like such:

void *ptr;

Points to a variable of unknown type.

Here we define an array of bytes (Remember, the type 'char' always weights 1 byte), of the size of the type 'int':

int bytes[sizeof(int)];

We make the 'void' pointer point to the beginning of the array:

ptr = bytes;

By explicitly casting the 'void' pointer to a pointer of type 'int', we can use the array as if it was a variable of type 'int':

int *intPtr = (int*)ptr; *intPtr = 60;

To avoid creating an other pointer, we can also write:

*((int*)ptr) = 60;

Above, we cast the pointer to a pointer of type 'int'. Then we access the 'variable' that it points to and we assign the value 60 to the array of bytes that is interpreted as a variable of type 'int'.

Dynamically allocating memory

malloc

The function 'malloc' returns a pointer of type 'void', pointing to a dynamically allocated byte array of the size of the number it received in argument.

The function 'malloc' is declared in the header file <stdlib.h>:

#include <stdlib.h>

Here we allocate 50 bytes:

malloc(50);

Here we allocate enough bytes for 10 variables of type 'float' and we cast the returned pointer to a pointer of type 'float':

float *floatArray = (float*) malloc(10 * sizeof(float));

We access the first element of the array:

floatArray[0] = 67;

And the last one:

floatArray[9] = 15;

Realloc

Using the function 'realloc', we can change the size of an array allocated with malloc:

1
2
3
4
5
// Allocates 4 'int'. int *intArray = (int*) malloc(4 * sizeof(int)); // Changes the size to 8 'int'. intArray = (int*) realloc(intArray, 8 * sizeof(int));

free

Unlike statically allocated memory, dynamically allocated memory must be manually freed. When we are done using memory allocated with 'malloc', we must free it using the function 'free':

free(intArray);