Reinterpreting Memory
Learn more about the inner workings of memory by learning to reinterpret data types.
We'll cover the following...
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 ofint
). We change the stack pointeresp
register by subtracting 4 (pushing the stack). - When we create a variable on the heap, we use
malloc
orcalloc.
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));
...