Unit 13
Dynamic Memory Allocation
How Memory Management in C works?
When you declare a variable using a basic data type, the C compiler automatically allocates memory space for the variable in a pool of memory called the stack.
For example, a float variable takes typically 4 bytes (according to the platform) when it is declared. We can verify this information using the sizeof operator as shown in below example
#include <stdio.h>
Int main() { float x; printf("The size of float is %d bytes", sizeof(x)); return 0;}
The output will be:
The size of float is 4 bytes
Also, an array with a specified size is allocated in contiguous blocks of memory, each block has the size for one element:
#include <stdio.h>
Int main() { float arr[10];
Printf("The size of the float array with 10 element is %d", sizeof(arr)); return 0;}
The result is:
The size of the float array with 10 element is 40
As learned so far, when declaring a basic data type or an array, the memory is automatically managed. However, there is a process for allocating memory which will permit you to implement a program in which the array size is undecided until you run your program (runtime). This process is called "Dynamic memory allocation."
Dynamic Memory Allocation
Dynamic Memory Allocation is manual allocation and freeing of memory according to your programming needs. Dynamic memory is managed and served with pointers that point to the newly allocated memory space in an area which we call the heap.
Now you can create and destroy an array of elements dynamically at runtime without any problems. To sum up, the automatic memory management uses the stack, and the dynamic memory allocation uses the heap.
The <stdlib.h> library has functions responsible for dynamic memory management.
Function | Purpose |
Malloc | Allocates the memory of requested size and returns the pointer to the first byte of allocated space. |
Calloc | Allocates the space for elements of an array. Initializes the elements to zero and returns a pointer to the memory. |
Realloc | It is used to modify the size of previously allocated memory space. |
Free | Frees or empties the previously allocated memory space. |
Let's discuss the above functions with their application
The malloc Function
The malloc() function stands for memory allocation. It is a function which is used to allocate a block of memory dynamically. It reserves memory space of specified size and returns the null pointer pointing to the memory location. The pointer returned is usually of type void. It means that we can assign malloc function to any pointer.
Syntax
Ptr = (cast_type *) malloc (byte_size);
Here,
- Ptr is a pointer of cast_type.
- The malloc function returns a pointer to the allocated memory of byte_size.
Example: ptr = (int *) malloc (50)
When this statement is successfully executed, a memory space of 50 bytes is reserved. The address of the first byte of reserved space is assigned to the pointer ptr of type int.
Consider another example:
#include <stdlib.h>
Int main(){
Int *ptr;
Ptr = malloc(15 * sizeof(*ptr)); /* a block of 15 integers */
If (ptr != NULL) {
*(ptr + 5) = 480; /* assign 480 to sixth integer */
Printf("Value of the 6th integer is %d",*(ptr + 5));
}
}
Output:
Value of the 6th integer is 480
- Notice that sizeof(*ptr) was used instead of sizeof(int) in order to make the code more robust when *ptr declaration is typecasted to a different data type later.
- The allocation may fail if the memory is not sufficient. In this case, it returns a NULL pointer. So, you should include code to check for a NULL pointer.
- Keep in mind that the allocated memory is contiguous and it can be treated as an array. We can use pointer arithmetic to access the array elements rather than using brackets [ ]. We advise to use + to refer to array elements because using incrementation ++ or += changes the address stored by the pointer.
Malloc function can also be used with the character data type as well as complex data types such as structures.
The free Function
The memory for variables is automatically deallocated at compile time. In dynamic memory allocation, you have to deallocate memory explicitly. If not done, you may encounter out of memory error.
The free() function is called to release/deallocate memory. By freeing memory in your program, you make more available for use later.
For example:
#include <stdio.h>
Int main() {
Int* ptr = malloc(10 * sizeof(*ptr));
If (ptr != NULL){
*(ptr + 2) = 50;
Printf("Value of the 2nd integer is %d",*(ptr + 2));
}
Free(ptr);
}
Output
Value of the 2nd integer is 50
The calloc Function
The calloc function stands for contiguous allocation. This function is used to allocate multiple blocks of memory. It is a dynamic memory allocation function which is used to allocate the memory to complex data structures such as arrays and structures.
Malloc function is used to allocate a single block of memory space while the calloc function is used to allocate multiple blocks of memory space. Each block allocated by the calloc function is of the same size.
Syntax:
Ptr = (cast_type *) calloc (n, size);
- The above statement is used to allocate n memory blocks of the same size.
- After the memory space is allocated, then all the bytes are initialized to zero.
- The pointer which is currently at the first byte of the allocated memory space is returned.
Whenever there is an error allocating memory space such as the shortage of memory, then a null pointer is returned.
The program below calculates the sum of an arithmetic sequence.
#include <stdio.h>
Int main() {
Int i, * ptr, sum = 0;
Ptr = calloc(10, sizeof(int));
If (ptr == NULL) {
Printf("Error! memory not allocated.");
Exit(0);
}
Printf("Building and calculating the sequence sum of the first 10 terms \ n ");
For (i = 0; i < 10; ++i) { * (ptr + i) = i;
Sum += * (ptr + i);
}
Printf("Sum = %d", sum);
Free(ptr);
Return 0;
}
Result:
Building and calculating the sequence sum of the first 10 terms
Sum = 45
Calloc vs. Malloc: Key Differences
The calloc function is generally more suitable and efficient than that of the malloc function. While both the functions are used to allocate memory space, calloc can allocate multiple blocks at a single time. You don't have to request for a memory block every time. The calloc function is used in complex data structures which require larger memory space.
The memory block allocated by a calloc function is always initialized to zero while in malloc it always contains a garbage value.
The realloc Function
Using the realloc() function, you can add more memory size to already allocated memory. It expands the current block while leaving the original content as it is. Realloc stands for reallocation of memory.
Realloc can also be used to reduce the size of the previously allocated memory.
Syntax
Ptr = realloc (ptr,newsize);
The above statement allocates a new memory space with a specified size in the variable newsize. After executing the function, the pointer will be returned to the first byte of the memory block. The new size can be larger or smaller than the previous memory. We cannot be sure that if the newly allocated block will point to the same location as that of the previous memory block. This function will copy all the previous data in the new region. It makes sure that data will remain safe.
For example:
#include <stdio.h>
Int main () {
Char *ptr;
Ptr = (char *) malloc(10);
Strcpy(ptr, "Programming");
Printf(" %s, Address = %u\n", ptr, ptr);
Ptr = (char *) realloc(ptr, 20); //ptr is reallocated with new size
Strcat(ptr, " In 'C'");
Printf(" %s, Address = %u\n", ptr, ptr);
Free(ptr);
Return 0;
}
Whenever the realloc results in an unsuccessful operation, it returns a null pointer, and the previous data is also freed.
Dynamic Arrays
A Dynamic array allows the number of elements to grow as needed. They are widely used in Computer science algorithms.
In the following program, we create and resize an array dynamically
#include <stdio.h>
Int main() {
Int * arr_dynamic = NULL;
Int elements = 2, i;
Arr_dynamic = calloc(elements, sizeof(int)); //Array with 2 integer blocks
For (i = 0; i < elements; i++) arr_dynamic[i] = i;
For (i = 0; i < elements; i++) printf("arr_dynamic[%d]=%d\n", i, arr_dynamic[i]);
Elements = 4;
Arr_dynamic = realloc(arr_dynamic, elements * sizeof(int)); //reallocate 4 elements
Printf("After realloc\n");
For (i = 2; i < elements; i++) arr_dynamic[i] = i;
For (i = 0; i < elements; i++) printf("arr_dynamic[%d]=%d\n", i, arr_dynamic[i]);
Free(arr_dynamic);
}
Result at the screen:
Arr_dynamic[0]=0
Arr_dynamic[1]=1
After realloc
Arr_dynamic[0]=0
Arr_dynamic[1]=1
Arr_dynamic[2]=2
Arr_dynamic[3]=3
Summary
- We can dynamically manage memory by creating memory blocks as needed in the heap
- In dynamic memory allocation, memory is allocated at a run time.
- Dynamic memory allocation permits to manipulate strings and arrays whose size is flexible and can be changed anytime in your program.
- It is required when you have no idea how much memory a particular structure is going to occupy.
- Malloc is a dynamic memory allocation function which stands for memory allocation that blocks of memory with the specific size initialized to a garbage value
- Calloc is a contiguous memory allocation function that allocates multiple memory blocks at a time initialized to 0
- Realloc is used to reallocate memory according to the specified size.
- Free function is used to clear the dynamically allocated memory.