Allocating new memory
Let's first address the first of these problems -
we do not know, until the function is called,
how big the array should be.
It is often the case that we do not know,
until we execute our programs,
how much memory we'll really need!
Instead of using a fixed sized array whose size may sometimes be too small,
we must dynamically request some new memory at
runtime to hold our desired result.
This is a fundamental (and initially confusing) concept of most
programming languages - the ability to request from the operating system
additional memory for our programs.
C11 provides a small collection of functions to support memory
allocation.
The primary function we'll see is named malloc(),
which is declared in the standard <stdlib.h>
header file:
#include <stdlib.h>
extern void *malloc( size_t nbytes );
|
- malloc() is a function (external to our programs)
that returns a pointer.
However,
malloc() doesn't really know what it's returning a pointer to -
it doesn't know if it's a pointer to an integer,
or a pointer to a character,
or even to one our own user-defined types.
For this reason, we use the generic pointer,
pronounced "void star" or "void pointer".
It's a pointer to "something",
and we only "know" what that is when we place an interpretation
on the pointer.
- malloc() needs to be informed of the amount of memory that it
should allocate - the number of bytes we require.
We use the standard datatype size_t to hold an integer
value that may be 0 or positive (we obviously can't request a negative
amount of memory!).
We have used, but skipped over, the use of size_t before -
it's the datatype of values returned by the sizeof operator,
and the pedantically-correct type returned by
the strlen() function.
CITS2002 Systems Programming, Lecture 12, p4, 28th August 2024.
|