Malloc (or ‘memory allocation’) is an exceptionally useful tool in C that allows the programmer to create dynamically behaving arrays and structures within their program. So, how does it work?
If you imagine that when a program is made, it uses up ‘blocks’ of standard memory simply for it to run (while this is often minute, it’s still important to take into account). Memory is used upon compilation based on the number of instantiated variables within the code (ints, chars etc). This use of memory can be visualised as a grid with each block of memory available/used as squares within this grid. What malloc does is tell the program to ‘set aside’ a given number of blocks of memory for later or current use.
Using malloc
When using malloc, there are two things to take into account. These are:
- Casting malloc to the variable type you wish to make dynamic.
- The size of each block of memory you are setting aside.
When calling malloc on a variable, you want to tell it what kind of variable it is. This is done by ‘casting’ malloc.
Different variables hold different sizes of memory. For example, an int has a size of four bytes. Telling malloc how large each block of memory needs to be is very important. If you do not do this, you will have problems trying to get the code to work in the way you wanted.
When using malloc, C is very intelligent when it comes to creating the dynamic arrays. Due to the nature of C89 programming, you must define a size for each array you instantiate within your code. This means that a dynamic array is structured a little differently. This is where pointers come in.
Pointers
A pointer is not a variable that holds a specific value. Instead, it points to a location in memory being held by the type of variable that it is. For example:
int *my_pointer;
This doesn’t allow storage of a value of type ‘int’. Instead, it ‘points’ to the location in memory for an int.
Why use pointers then? Simple; malloc assigns blocks of memory to a variable, but as this variable is going to be of unknown size at the time of compilation, you want the pointer to at least know where the memory is.
Two simple steps to making your own dynamic array
- Instantiate two variables; One of type int (which will be a storage for the number of elements you want in your array), and the other being a pointer of the type of variable you wish to store within your array.
- When you have decided on how many elements your array will have, you need to malloc the pointer to point to that number of blocks of memory. Don’t forget to CAST the malloc!
my_array = (int*)malloc(bits_of_memory * sizeof(int));
int bits_of_memory, *my_array;
What is going on here? When you are assigning malloc to your array pointer, note that you have to cast it to the type of variable that it is. In this case, it’s a pointer to an int (i.e. ‘int*’). The number of blocks of memory is then reliant on the value of ‘bits_of_memory’. This is then multiplied by the total size of a single integer (four bytes).
If you imagine that the variable ‘bits_of_memory’ had a value of 4, malloc will set aside “4 ‘times’ the size of the variable” blocks of memory for you:
[int][int][int][int][ ][ ][ ]
And it’s that simple! Yes, it really is. As long as you remember the type of variables you’re playing around with, malloc will allow you to dynamically set aside blocks of memory.
Handling the array
As mentioned before, C is very intelligent when handling dynamic arrays. The moment you use malloc on a pointer, it automatically assumes you want to turn it into an array. This means that you can now use the variable like an array.
my_array[0] is completely legal.
In the example program below, I have placed the reading into and printing of the variable into a for loop. This makes handling the array on a complete scale a lot easier, especially if you want to place all of the information in in one go.
Example program:
/*
* File: main.c
* Author: Josh Greatrex
*
* Created on 08 February 2010, 16:08
*
* This file should give you a basic working knowledge of how malloc works
* and how it can be used in C programming. Please feel free to copy this
* source code and compile it yourself.
*/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int main() {
int bits_of_memory, *my_array, i;
printf("How big do you want this array to be? ");
scanf("%d", &bits_of_memory);
/* Allocates memory for the array */
my_array = (int*)malloc(bits_of_memory * sizeof(int));
/* Allows the user to enter the values into the array */
for(i = 0; i < bits_of_memory; i++) {
printf("Enter the value for element %d: ", (i+1));
scanf("%d", &my_array[i]);
}
/* Prints off all of the element values from the array */
for(i = 0; i < bits_of_memory; i++) {
printf("Value for element %d is %d\n", (i+1), my_array[i]);
}
return 0;
}