Dynamic Memory Allocation in C: Usage and Examples

Rumman Ansari   Software Engineer   2024-07-05 04:11:50   9907  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

Before Learning dynamic memory allocation You Should Know about pointer

C language requires the number of elements in an array to be specified at compile time. But we may not be able to do so always. Our initial judgment of size, if it is wrong, may cause failure of the program or wastage of memory space.

In C, the exact size of an array is unknown until compile time, i.e., the time when a compiler compiles our code into a computer understandable language. So, sometimes the size of the array can be insufficient or more than required.


But dynamic memory allocation allows your program to obtain more memory space while running, or to release it if it's not required.



Dynamic data structure provides flexibility in adding, deleting or rearranging data items at runtime. Dynamic memory management techniques allow us to allocate additional memory space or to release/free unwanted space at run time.

The process of allocating memory at runtime is known as dynamic memory allocation. Library routines known as "memory management functions" are used for allocating and freeing memory during execution of a program.


C language offers 4 dynamic memory allocation functions. They are below,
Function Description
malloc() allocates requested size of bytes and returns a void pointer pointing to the first byte of the allocated space
calloc() allocates space for an array of elements, initialize them to zero and then returns a void pointer to the memory
free releases previously allocated memory
realloc modify the size of previously allocated space

Sample Code

Function
Syntax
malloc () malloc (number *sizeof(int));
calloc () calloc (number, sizeof(int));
free () free (pointer_name);
realloc () realloc (pointer_name, number * sizeof(int));

Memory Allocation Process

Before we discuss these functions, let us look at the allocation process associated with c program.

Global variables, static variables and program instructions get their memory in permanent storage area whereas local variables are stored in a memory area called Stack. The memory space between these two region is known as Heap area. This region is used for dynamic memory allocation during execution of the program. The size of heap keep changing.

Conceptual view of the storage of c program

Before learning above functions, let's understand the difference between static memory allocation and dynamic memory allocation.

Static memory allocation Dynamic memory allocation
Memory is allocated at compile time. Memory is allocated at run time.
Memory can't be increased while executing the program. Memory size is fixed Memory can be increased while executing the program. Memory can be created dynamically.
Used in the Array. Used in the Linked list.

Allocating block of Memory

A block of memory can be allocated using the function malloc.

The name malloc stands for "memory allocation".

This function reserves a block of memory of given size and returns a pointer of type void.

This means that we can assign it to any type of pointer using typecasting. If it fails to allocate enough space as specified, it returns a NULL pointer.

malloc () does not initialize the memory allocated during execution. It carries garbage value.

Syntax:

	void* malloc(byte-size)
	

The function malloc() reserves a block of memory of specified size and return a pointer of type code>void which can be casted into pointer of any form.

	ptr = (cast-type *) malloc(byte-size);
	

Example using malloc() :

	int *ptr;
	ptr = (int*)malloc(50 * sizeof(int));    //memory space allocated to variable ptr
	free(ptr);                    //releases the memory allocated to variable ptr
	

Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.

	ptr = (int*) malloc(100 * sizeof(int));
	

This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the pointer points to the address of first byte of memory.

Example program for malloc() fuction in C

	
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
 
int main()
{
     char *ptr;
     /* memory is allocated dynamically */
     ptr = malloc( 10 * sizeof(char) );
     if( ptr== NULL )
     {
        printf("Couldn't able to allocate requested memory\n");
     }
     else
     {
        strcpy( ptr,"atnyla.com");
     }
     printf("Dynamically allocated memory content : " \
            "%s\n", ptr );
     free(ptr);
}
	
 
Output:
Dynamically allocated memory content : atnyla.com
Press any key to continue . . .
 

Another Example of Dynamically memory allocation for array

In this program User can create memory at heap using dynamic memory allocation process through malloc() function

	
#include <stdio.h>  
#include <stdlib.h>  
void main(){  
    int n,i,*ptr,sum=0;  
    printf("Enter number of elements: ");  
    scanf("%d",&n);  
    ptr=(int*)malloc(n*sizeof(int));  //memory allocated using malloc  
    if(ptr==NULL)                       
    {  
        printf("Unable to allocate memory");  
        exit(0);  
    }  
    printf("Enter elements of array: \n");  
    for(i=0;i<n;++i)  
    {  
        scanf("%d",ptr+i);  
        sum+=*(ptr+i);  
    }  
    printf("Sum=%d \n",sum);  
    free(ptr);  
}  
	
 
Output:
Enter number of elements: 5
Enter elements of array:
1
2
3
4
5
Sum=15
Press any key to continue . . .
MCQ Available

There are 1 MCQs available for this topic.

1 MCQ