DS – Dynamic Memory Allocation in C

Memory Allocation in C:

  • Programs are used to store and process the information.
  • We use variables to store information.
  • We allocate memory to variables in 2 ways
    • Static Memory – Fixed memory to store information
    • Dynamic Memory – Size increase and decrease based on insertions & deletions.

stdlib.h:

  • It is a header file of C Library.
  • It contains 4 functions to allocate and de-allocate the memory dynamically.
  • malloc() : allocate memory to structure type variables.
  • calloc() : allocate memory to array type variables
  • realloc() : modify the size of array which is allocated by calloc()
  • free() : de-allocates the memory.

Pointer casting:

  • A pointer always points to specific type of data.
    • int* can points to integer type data only
    • struct Emp* can points to Emp type data only
    • Pointer casting is required to make one pointer points to another type of data.
#include<stdio.h>
int main()
{
            int x=10;
            int* p1;
            char* p2;
           
            p1 = &x;
            printf(“x value is : %d \n”, *p1);
           
            p2 = (char*)p1;
            printf(“x value is : %d \n”, *p2);
            return 0;          
}

size_t:

  • It is a datatype in C.
  • It represents unsigned integer(positive) value.
  • For example, strlen() method returns the length of specified string. The return type is size_t as the length of string always positive integer value
    • size_t  strlen(char* s)

malloc():

  • Allocate memory to structure variables dynamically
    • void*  malloc(size_t size)
  • We need to pass the size of the structure to allocate the memory.
  • On success, it allocates the memory and returns base address of memory block.
  • On failure, if no memory to allocate, it returns NULL pointer.

Why return type is void*?

  • malloc() function can allocate the memory to any type of structure such as Employee, Student, Account, Customer, Product etc.
  • The team of C developers specified common pointer type(as return type) as they don’t to what type of structure programmer allocate the memory.
  • Programmer need to convert the void* type to specific structure type.

Program to allocate memory dynamically to structure:

#include<stdio.h>
struct Emp
{
            int id;
            char name[20];
            float salary;
};
int main(){
            struct Emp* p;
            p = (struct Emp*)malloc(sizeof(struct Emp));
            if(p==NULL){
                        printf(“Out of memory \n”);
            }
            else{
                        printf(“enter emp details : \n”);
                        scanf(“%d%s%f”, &p->id, p->name, &p->salary);
                        printf(“Name is : %s \n”, p->name);
            }
            return 0;          
}

Default values of global variables:

  • Declaration of variable outside to all functions is called Global variable.
  • Global variable automatically initializes with default value based on the data type.
Data typeDefault Value
int0
charBlank
float0.000000
pointernull

Program to display default values of global variables:

#include<stdio.h>
int x;
int* p;
int main()
{
            printf(“int default value : %d \n”, x);
            printf(“pointer default value : %s \n”, p);
            return 0;          
}

calloc():

  • Calloc() function allocate memory to array type variables.
    • void*  calloc(size_t n , size_t size)

Parameters & return values:

  • First argument specifies the “size of array”
  • Second argument represents the “size of each element in array”
  • On success, it allocates n*size bytes memory and returns base address
  • On failure, it returns NULL pointer.

We need to typecase the void* type to array type:

Program to allocate memory to Array dynamically:

#include<stdio.h>
int main(){
            int* arr, n;
            printf(“Enter size of array : “);
            scanf(“%d”, &n);
            arr = (int*)calloc(n, sizeof(int));
            if(arr==NULL){
                        printf(“Out of memory \n”);
            }
            else{
                        int i;
                        printf(“Array elements are : \n”);
                        for(i=0 ; i<n ; i++){
                                    printf(“%d \n”, *(arr+i));
                        }
            }
            return 0;          
}

Accessing elements: when pointer points to array, we should not use indices.

Another way of accessing elements: we repeat the loop with pointers to access the elements of array as follows.

#include<stdio.h>
#include<stdlib.h>
int main(){
            int *arr, n;
            printf(“Enter initial size of array : “);
            scanf(“%d” , &n);
            arr = (int*)calloc(n , sizeof(int));
            if(arr==NULL)
                        printf(“Out of memory \n”);
            else{
                        int *i;
                        printf(“Array elements are : \n”);
                        for(i=arr ; i<arr+n ; i++)
                                    printf(“%d \n”, *i);
            }          
            return 0;          
}

Program to read the elements into array:

#include<stdio.h>
#include<stdlib.h>
int main()
{
            int *arr, n;
            printf(“Enter initial size of array : “);
            scanf(“%d” , &n);
            arr = (int*)calloc(n , sizeof(int));
            if(arr==NULL){
                        printf(“Out of memory \n”);
            }
            else{
                        int i;
                        printf(“Enter %d elements : \n”, n);
                        for(i=0 ; i<n ; i++){
                                    scanf(“%d”, arr+i);
                        }
                        printf(“Array elements are : \n”);
                        for(i=0 ; i<n ; i++){
                                    printf(“%d \n”, *(arr+i));
                        }
            }          
            return 0;          
}

realloc():

  • Using calloc(), we can allocate only fixed size of memory to array.
  • To modify the size of array dynamically, we use realloc() function.
  • Prototype is:
    • void*  realloc(void* p, size_t size);

free():

  • It is used to de-allocate the memory
  • Prototype is :
    • void  free(void* p);
  • free() function is giving information to memory allocator(OS) about the memory released in this program. So that the released memory can allocate to another variable.

Scroll to Top