Reinterpreting Memory

Learn more about the inner workings of memory by learning to reinterpret data types.

Introduction

We know by now that memory is a linear sequence of bits or bytes.

We also know the following:

  • When we create a variable on the stack, say int x, we allocate a block of memory of 4 bytes (the size of int). We change the stack pointer esp register by subtracting 4 (pushing the stack).
  • When we create a variable on the heap, we use malloc or calloc. These functions only need to know the size of the memory block to allocate it.

From the points mentioned above, we can deduce that no matter how we allocate data, the only important thing is how many bytes we need for that particular data type.

The memory itself has no concept of data types. It’s just a sequence of 0 and 1. The memory doesn’t care if 0 and 1 come from an int or a double. We choose how to interpret the data depending on which data type we use in our code.

For example:

malloc(sizeof(int));
malloc(4 * sizeof(char));

Both malloc calls will allocate a memory block of 4 bytes. It’s up to us if we want to interpret these 4 bytes as one integer or as an array of four characters. The following interpretations are valid:

int* p1 = malloc(sizeof(int));
char* p2 = malloc(4 * sizeof(char));

We can even mix them:

char* p1 = malloc(sizeof(int));
int* p2 = malloc(4 * sizeof(char));

Sure, doing so is confusing, and it isn’t something we should do in practice. But the important thing is that it works. Both sizeof(int) and 4 * sizeof(char) yield a block of 4 bytes, and we can choose how to interpret it, either as an integer or as an array of four characters.

See the following memory drawing:

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy