- When a program needs storage, you allocate it
in the code by setting aside space for a variable.
When you need more than one variable, you create an array.
And when you don't know how much space you need, you guess.
But there's a better way.
In this movie, I cover the topic
of allocating storage in your code.
You'll see how to properly ask for storage,
determine that it's available,
and then access that storage in your code.
Storage is divvied up by the operating system.
Your program asks for space as it needs it.
This request is made in one of two ways.
The first way is to declare a variable.
Storage for the variable is set aside
and made available for use.
And for a specific purpose in the code.
This code declares several variable types.
Including an empty character buffer.
The sizeof operator is then used to calculate
how much storage is set aside.
Build and run this code.
On my computer, it shows that 141 bytes
of storage were set aside.
Even though the storage is never used,
save for the total variable, it's still set aside.
Your computer may show a different total,
depending on how memory is allocated
by the operating system.
When you don't know how much storage you need,
then you can allocate it on the fly.
The function that does that is called malloc.
Which sounds like a bad guy name,
but it's really short for "memory allocation".
Open exercise file allocate2.
The malloc function appears at line 10.
It requires the stdlib header file,
which is included at line two.
The format is to allocate a chunk of memory,
but you need to know how much.
So you take the variable type, which is char here.
And you get the size of that variable type.
Then you multiply it by how much storage you need.
Here the SIZE constant is used.
The malloc function then returns a memory location.
A pointer where the storage has been allocated in memory.
Here, that location is saved in pointer variable sto.
It must also be the same type of variable
as for the chunk of memory allocated.
One more piece is needed.
You must type-cast the memory location returned
to match the pointer variable type
on the other side of the assignment operator.
A type-cast is forcing one type of variable
to masquerade as another.
And doing so avoids some compiler warnings.
Before the malloc function, you need to type char.
This type-cast ensures that the compiler understands
a character pointer is being assigned.
That's char, which is the variable type.
And the pointer operator,
which ensures that it's a memory location.
Save this change, build, and run.
And 1024 bytes of storage are allocated
at a given memory location.
If they weren't allocated, then the malloc function
would have assigned a NULL pointer value to variable sto.
That condition is checked for in line 11.
Always check for this condition.
You can use the NULL constant.
You don't want a program to use memory that's not available.