Allocating Memory
With dynamic memory management, one of the tasks you can perform is to request space from the heap. With this request, the operating system will locate available space and allocate this to you for use in your code. The only thing the operating system really needs to know is how much space you require? It can then search for a free space of that size, allocate this to you, and then give you the address of (a pointer to) this newly allocated area of memory.
Memory Allocation: Why, When, and How
If you want to load a value onto the heap, you use these memory allocation functions to allocate you space. Once you have the space allocated, you can access it via the pointer you receive back from the functions.
In C/C++
C includes two memory allocation functions: malloc
, and calloc
. Let’s see how each of these work.
Function | Required Arguments | Returns | Description |
---|---|---|---|
malloc | the size in bytes that you want. | a pointer (void * ) | Allocates memory and returns a pointer to it. |
calloc | the number of items, and the size of each item | a pointer (void * ) | Allocates and clears memory, returning a pointer to the space allocated. |
These functions are used in combination with the sizeof
operator. You can use sizeof
to get the number of bytes that a data type or variable requires.
Allocate memory with malloc
The malloc
function is declared within stdlib.h. It has the following function prototype.
malloc
is the standard memory allocation function in C. You tell it how much space you want, it allocates you that many bytes on the heap, and returns a pointer to that address.
The following example demonstrates the use of malloc
to store an integer value on the heap. In this case we use malloc
to allocate sufficient space to store an integer on the heap. The sizeof
operator can give us the size of an integer, which we can then pass to malloc
to ensure we ask for the right number of bytes. The result returned from malloc
is a void pointer (an untyped pointer), so we need to cast this to be an int
pointer (int *
).
Allocate memory with calloc
Like malloc
, calloc
is used to allocate space on the heap. The difference between calloc
and malloc
is that calloc
clears the memory allocation. This will ensure that each byte in the space allocated is set to 0. Whereas, with malloc
any previous values that happen to have been in memory will remain there giving the value a seemingly random value.
The other difference with calloc
is that you pass it both a number, and a size. This allows you to allocate arrays easily with calloc
, as it returns you a pointer to a block of memory that is number x size
bytes.