Table of Contents
In this lesson, you will learn about memory allocation in C. We will go through the malloc()
, calloc()
, free()
, and realloc()
functions that can be found in the <stdlib.h>
header file, along with examples to better understand the topic.
Memory Management and Allocation
When declaring a variable in C, most compilers automatically allocate a memory block for the variable in an area called the stack, where all temporary variables are stored.
#include <stdio.h> int main() { int a; printf("The size of int is %d byte(s)", sizeof(a)); return 0; }
Output
The size of int is 4 byte(s)
Better yet, declaring an Array in C can have an initial size of Data Types as we learned from the lesson One-dimensional Array in C. But, what if you, the programmer, don’t know what the array’s length should be? What if you declare an array of size of 100, while you only need 20 at most? This is where a memory allocation is needed for better performance and memory space usage.
When Memory Allocation is needed?
A desktop application environment where a memory size can be huge may not be a big deal to reallocate memory (not a great practice). But if you are writing a program for an ABS where memory size is limited, you will need a better memory management strategy to get the best of the small memory size provided to you.
Dynamic Memory Allocation in C
When you are writing a computer program, you should find the best way to allocate and free memory blocks based on your program needs. in C, <stdlib.h>
library contains functions that are created for Dynamic Memory Allocation purposes. We will go into detail about these functions in the next section.
Dynamic Memory Allocation Functions
The table below illustrates the functions that are responsible for dynamic memory allocation in the <stdlib.h>
library:
Function | Description |
---|---|
malloc() | Allocates the memory of the requested size. |
calloc() | Allocates the memory of the requested size and sets the allocated memory to zero. |
realloc() | Modifies the size of a previously allocated memory space with malloc() or calloc(). |
free() | It frees or deallocates the previously allocated memory space with a malloc() or calloc() or realloc() |
The malloc() function
The malloc()
function, known as the memory allocation function, is used to assign a specified number of bytes to an array upon creation.
syntax of malloc()
myPointer = (cast type *) malloc(byte size);
Example
intPointer= (int *) malloc (20);
The code above reserves 20 bytes in the memory, then assigns the first byte to the pointer intPointer.
Example of malloc() in C
#include <stdio.h> #include <stdlib.h> int main() { int * intPointer; intPointer = (int * ) malloc(10 * sizeof(int)); if (intPointer == NULL) { printf("Error. Memory not allocated. \n"); } else { printf("Address of the pointer is %d\n ", intPointer); for (int i = 0; i < 5; i++) { intPointer[i] = i; } for (int i = 0; i < 5; i++) { printf("%d\n", intPointer[i]); } } }
Output
Address of the pointer is 34267152
0
1
2
3
4
The calloc() function
The calloc()
function, or contiguous allocation function, is used to allocate more than one memory block. The calloc()
is mainly used to allocated complex data structures such as linked lists and structs. All blocks allocated by the calloc()
function have the same size.
Syntax of calloc()
myPointer = (cast_type *) calloc (n, size);
where n is the number of blocks to be allocated.
Example
floatPointer= (float*) calloc(15, sizeof(float));
Will allocate contiguous block in memory for 15 elements of type float
Example of calloc()
#include <stdio.h> #include <stdlib.h> int main() { int i; int * intPointer; int sum = 0; intPointer = calloc(10, sizeof(int)); if (intPointer == NULL) { printf("Error. Memory not allocated."); return 0; } printf("Calculating the sequence sum of the first 5 terms \n "); for (i = 0; i < 5; ++i) { *(intPointer + i) = i; sum += * (intPointer + i); } printf("Sum = %d", sum); return 0; }
Output
Calculating the sequence sum of the first 5 termsSum = 10
The realloc() Function
The realloc()
function, known as the reallocation function, is used when more memory size is needed for a previously allocated size. The realloc function can also be used to reduce the size of the allocated memory.
Syntax of realloc()
myPointer= realloc(myPointer, n);
Where n is the new size for the newly reallocated memory block.
Example of realloc()
#include <stdio.h> #include <stdlib.h> int main() { int * intPointer; int i; int size1; int size2; printf("Please enter size: "); scanf("%d", & size1); intPointer = (int * ) malloc(size1 * sizeof(int)); printf("Addresses original allocated memory is "); for (i = 0; i < size1; ++i) printf("%u\n", intPointer + i); printf("\nPlease enter the new size:"); scanf("%d", & size2); // rellocating the memory intPointer = realloc(intPointer, size2 * sizeof(int)); printf("Addresses of newly allocated memory is "); for (i = 0; i < size2; ++i) { printf("%u\n", intPointer + i); } return 0; }
Output
Please enter size: 4
Addresses original allocated memory is 19283984
19283988
19283992
19283996Please enter the new size: 3
Addresses of newly allocated memory is 19283984
19283988
19283992
The free() function
The free()
function is used to deallocate a memory block that was previously allocated by the malloc()
or realloc()
functions. Once a memory space is no longer needed, you should explicitly deallocate it using the free()
function. Otherwise, a stack overflow exception may occur.
Syntax of free()
free(myPointer);
Example of free()
#include <stdio.h> #include <stdlib.h> int main() { int * intPointer = malloc(50 * sizeof( * intPointer)); if (intPointer != NULL) { *(intPointer + 2) = 100; printf("The value of the 2nd integer is %d", *(intPointer + 2)); } free(intPointer); // frees the allocated space }
Output
The value of the 2nd integer is 100
Difference Between malloc() and calloc()
- calloc() makes the starting address of block zero, while malloc() does not.
- malloc() takes 2 arguments, while calloc() takes 1.
- malloc() performance is higher than calloc()
- calloc() performs a memory initialization, while malloc() does not.
- malloc() creates a single block of memory, while calloc() can assign multiple blocks of memory.
- malloc() is less secured compared to calloc()
Summary
- Dynamic Memory Allocation is essential for better memory management and usage.
- malloc(), calloc(), realloc(), and Free() are Dynamic Memory Allocation functions in the <stdlib.h> library.
- The malloc() function is used to allocate the memory of the requested size.
- The calloc() function is used to allocate the requested size memory and sets the allocated memory to zero.
- The realloc() function is used to modifies the size of a previously allocated memory space with malloc() or calloc()
- The free() function is used to deallocates the allocated memory space with a malloc() or calloc() or realloc()