This post covers dynamic memory allocation in C programming.
As a part of this we are going to discuss the below things in dynamic memory allocation in C in this post.
Resources are always a premium. The concept of dynamic memory allocation in C language enables the C programmer to allocate memory at run time.
The #include<stdlib.h>
provides four functions that can be used to manage dynamic memory.These four functions are calloc()
, malloc()
, free()
, realloc()
.
Pointers plays an important role in dynamic memory allocation in C programming because we can access the dynamically allocated memory only through pointers.
Difference Between Static Memory Allocation And Dynamic Memory Allocation In C:
Static Memory Allocation | Dynamic Memory Allocation |
---|---|
In static memory allocation, memory is allocated While Writing the C program. Actually, user requested memory will be allocated at compile time. | In dynamic memory allocation, memory is allocated While executing the program. That means at run time. |
Memory size can’t be modified while execution | Memory size can be modified while execution |
Example: array In an array, it is must to specify the size of the array While declaring, so the size of the array is fixed during runtime, int a [10]; In the above declaration 10×2=20 bytes of memory allocated (as per turbo compiler) to the array We can’t allocate memory to this array at runtime. | Example: Linked list int n = 10; // Number of bytes to allocate int *ptr; // Pointer Variable to store address ptr = (int *) malloc(n * sizeof(int)); // Allocate 10 × 2 bytes in memory |
Memory Layout of C Programs
Global variables are allocated in the global data section and are accessible from all parts of the program.
Local variables are allocated during execution on the run-time stack.
Heap is the segment where dynamic memory allocation usually takes place.The heap area begins at the end of the BSS segment and grows to larger addresses from there.The Heap area is managed by malloc, calloc,realloc, and free.
malloc()
Declaration: void *malloc(size_t size);
This function is used to allocate memory dynamically.The argument size specifies the number of bytes to be allocated.The type size_t is defined in stdlib.h .
On success, malloc()
returns a pointer to the first byte of allocated memory.
The allocated memory initially contains garbage value.
The returned pointer is void type,which can be type cast to appropriate type of pointer based on requirement.
In general ptr=(datatype *) malloc (required size);
In the above declaration ptr is a pointer of type datatype,and specified size is the size in bytes required to be reserved in memory. datatype * is used for typecast the pointer returned by malloc().
Example-: int *ptr;
ptr=(int *)malloc(8);
This allocates 8 contiguous bytes of memory space and the address of first byte is stored in the pointer variable ptr. This space can hold 4 integers.
Unlike memory allocated for variables and arrays, dynamically allocated memory has no name associated with it. So it can be accessed only through pointers. We have pointer which points to the first byte of the allocated memory and we can access the subsequent bytes using pointer arithmetic.
calloc()
Declaration : void *calloc(size_t n,size_t size);
The calloc function is used to allocate multiple blocks of memory.It takes two arguments the first argument specifies the number of blocks and the second one specifies the size of each block.
Example: ptr=(int *) calloc (4,sizeof(int));
//This allocates 4 blocks of memory ,each block contains 2 bytes of memory and starting address stored in the pointer variable ptr.
Memory allocated by calloc()
is initialized to zero.
Both malloc()
and calloc()
returns NULL if there is no sufficient memory available in the heap.
realloc()
We may required to increase or decrease the memory allocated by malloc() or calloc().The realloc() is used to change the size of the memory block .it alters the size of the memory block without losing old data.This is reallocation of memory.
Declaration : void *realloc(void *ptr,size_t newsize)
This function takes two arguments ,first is a pointer to the block of memory that was previously allocated by malloc() or calloc() & the second one is the new size for that block.
Example: ptr=(int *)malloc(size);
//this will allocates the memory of the specified size & the starting address of this memory block is stored in the pointer variable ptr.
if we want to change the size of memory block then we can do by below way
ptr=(int*) realloc(ptr,newsize);
This statement allocates the memory space of newsize of bytes & the starting address of this memory block is stored in the pointer variable ptr.
The newsize can be smaller or larger than the old size.
This function moves the contents of old block into the new block & the data of the old block is not lost.
On failure realloc()
returns NULL.
free()
The dynamically allocated memory is not automatically released, It will exit till the end of the program.
If the job of the dynamically allocated memory is finished then its our responsibility to release that memory so that it can be reused.
The free() is used to release the memory space allocated dynamically. After release the memory again available in the heap for reuse.
Declaration : void free(*p)
Example: free(ptr);
As and when the program terminates all the memory is released automatically by the operating system, but it is good practice to free whatever has been allocated dynamically. We won’t get any error if we dont free the dynamically allocated memory, but this would lead to memory leak.
We should not try to free any memory location that was not allocated by malloc()
, calloc()
or realloc()
.
Example program
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main ()
{
char *str;
/* Initial memory aLLocation*/ str = (char *) malloc(25);
strcpy(str, "Computers are useless.");
printf("string = %s, Address = %u\n", str, str);
/* ReaLLocating memory */ str = (char *) realloc(str,38);
strcat(str, "They can only give you answers.");
printf("String = %s, Address = %u\n", str, str);
/* DeaLLocate allocated memory */ free(str);
return(0);
}
Output:
That was all about Dynamic Memory Allocation in C, Have fun with C Programming!