Static memory allocation in C | Dynamic memory allocation in C
Written by
Memory Allocation in C – malloc, calloc, free, realloc
Introduction:
Just like every vehicle on the road, requires some free space in order to drive smoothly, likewise, every computer program or process requires some space in memory to execute. A process is assigned usually a physical or virtual address space for this purpose.
The structure of our computer’s memory space is used for a program’s execution is as depicted below:
Static Memory Allocation in C
As seen in the above representation, the global, static variables and program instructions occupy permanent storage space. The local variables, on the other hand, are located in the stack area. There is some amount of free memory between stack and permanent storage space whose size keeps varying, which is called heap. This location is reserved for run-time allocation or dynamic memory allocation.
- If Memory allocation is done before program execution, it is called static memory allocation.
- Also called as compile-time allocation as space allocation is done during compile time.
- When we know the size of variables, the size of array in advance then this type of allocation is useful.
- The memory allocated for such variables/array is from the stack area.
- From the beginning to the end of the program, this space will be reserved for those specific variables of that process.
- This memory space is denoted in C using variables and using them we can access its value.
- It is a fast process, saves running time.
- g: int a,b;
int array[10];
Dynamic Memory Allocation in C
- If memory is allocated during run-time, this type of allocation is called dynamic memory allocation.
- It is a slow process as memory has to be allocated while programming execution.
- Usually, a programmer during compile time might not know the exact memory requirements for the program.
- Hence in such situations, memory is allocated while the program executes as per the need.
- Memory allocation is done from the heap area which is an area whose size keeps varying as per requirement.
- The memory space can be allocated and released at any point in time.
- Here, the space allocation does not have a name; hence the value needs to be accessed only using pointers.
- The programmer has to be cautious of one thing here; C does not have automatic garbage collection, unlike Java.
- The programmer has to manually manage all dynamic memory while program execution.
- e.g:
p = malloc(sizeof(int)); //here space equivalent to integer data type will be allocated
Dynamic memory management in C
The <stdlib.h> provides four functions that can be used to manage dynamic memory in C:
Function | Use of Function |
malloc() | Allocates requested size of bytes and returns a pointer (void*) to memory |
calloc() | Allocates space for array elements, initializes to zero and then returns a pointer to the memory |
free() | De-allocates the previously allocated space |
realloc() | Changes the size of previously allocated space |
calloc() in C
- malloc() stands for memory allocation.
- It allocates ‘size_in_bytes’ of memory from the heap area, if the allocation succeeds it returns a pointer (void*) to the block of memory else it returns NULL.
- It allocates a contiguous block of memory, if those many continuous blocks are not available then a NULL pointer is returned. Therefore always check if memory allocation was successful or not as given below:
void* p;
if ((p=malloc(n)) == NULL)
return 1;
else
{//successful memory allocation}
malloc() returns uninitialized memory to use, i.e memory which has garbage values.
Function Definition:
void *malloc(size_t size);
malloc takes in a size-t and returns a void pointer.
Syntax:
ptr=(cast-type*)malloc(byte-size)
‘ptr’ will be pointer of the cast-data-type.
Example:
#include<stdio.h>
int main()
{
int a, *ptr;
printf("Enter a number\n");
scanf("%d",&a);
ptr = (int*)malloc(a*sizeof(int));
if (ptr==NULL)
printf("Memory allocation not sucessful");
else
{
printf("Success in memory allocation\n");
printf("Value of a is: %d\n", a);
}
}
Here, we have used malloc to allocate space of ‘a’ times int data type number of bytes.
- calloc() means contiguous allocation.
- It allocates multiple blocks of memory each of the same size unlike malloc() which allocates only a single block of memory.
- All the blocks of memory are initialized to zero.
- It allocates memory region to hold size_of_block, if allocation is successful pointer to the block of memory is returned else NULL is returned
Function:
void *calloc(size_of_block, size_t size);
Allocates memory for an array of members equal to size_of_block elements each of
size_t and returns a pointer to the allocated memory.
- calloc(num, sizeof(int)) is equivalent to malloc(num*sizeof(int))
- Usually used to initialise array during run-time.
Syntax:
ptr = (cast-type*)calloc(num, element-size);
Space will be allocated equivalent to array of num elements.
Example:
#include<stdio.h>
int main()
{
int a, *ptr;
a = 10;
ptr = (int*)calloc(a, sizeof(int));
if (ptr==NULL)
printf("Memory allocation not sucessful");
else
{
printf("Success in memory allocation\n");
printf("Size of array is: %d\n", a);
}
}
Here, memory equivalent to an array of 10 elements of integer data type i.e 4 bytes each would be allocated.
free() in C
- A lot of times memory that has been allocated for a process/ program is not released back properly once it is no longer in use. This is called memory leaks.
- Such leaks can lead to unexpected system crashes as well.
- In C, memory allocated using malloc(), calloc(), realloc() needs to be released back to Operating system once its use is over, else that space would be consumed otherwise even when not required. This is done using free().
Function:
void free(void *pointer);
Syntax:
free (ptr);
Here, the memory block pointed by the pointer ‘ptr’ would be released back to the system.
realloc() in C
- As the name suggests, it is used to reallocate memory with a specified new size.
- It basically modifies the size of the memory block pointed by pointer ‘ptr’ to given new size_in_bytes.
- It allows us to expand or reduce the memory space we wish to use.
- Used when we wish to resize memory block previously allocated using malloc() and calloc().
- When using realloc(), chances are that a separate space than current will be chosen for the modified size; here the previous memory block is copied to new and once done released automatically.
Syntax:
ptr=realloc(ptr, new-size);
Example:
#include<stdio.h>
int main()
{
int a, *ptr;
a = 10;
ptr = (int*)malloc(a*sizeof(int));
ptr = (int*)realloc(ptr, 20);
if (ptr==NULL)
printf("Memory allocation not successful");
else
{
printf("Success in memory allocation\n");
printf("Size of array is: %d\n", a);
}
}
Instead of 10 * 4 bytes, 20*4 bytes will be the space occupied in memory by ptr.