C Memory Management

C memory management

Static memory allocation

static memory allocation is allocation of memory before program execute. this memory are allocated at compile time.

Automatic memory allocation

stack are use to automatic memory allocation. stack area is a computer memory utilized by program to execute functions and their local variable. stack is follow the rule of (LIFO). When calling a user defined function this function are push on to stack area and similarly inserting local variable of those function. let as view this example. in this program we are print recursive number from 1 to 10.

/*
  System stack example
*/
#include<stdio.h>
/*Declaration of function*/
void print(int num);

/*Display number 1-10*/
void print(int num){
  if(num<=10){
    printf(" %d\n",num++);
    print(num); //call print function
  }
}
int main()
{
  //start execution
  //local variable of main
  int value=1;

  //call print function
  print(value);
  return 0;
}

Output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
recursive function call

In this example view. main() function are first inserted on stack area. and their local variables. main() function is calling to print() function. then next inserted function is print() function in stack area. so conclusion is recursion and user defined function are use space or memory of stack area.
1) Stack area are managed by program. they are allocating and free their memory.
2) Stack are has limited. when recursive call infinite then stack will be overflow. and end of execution.

Dynamic memory allocation

Heap area is reserved by dynamic memory allocation. the programmer are utilize for this area. Most of data structure are depends on need to create dynamic memory. for example we are create a dynamic array in size of 10 integers.

dynamic memory allocation heap
/* 
  Dynamic allocation of array example
*/
/*Header file*/
#include <stdio.h>
#include <stdlib.h>

/*Global variables*/
int size=10;
int main(){
  /*Entry point of program*/
  /*Dynamic allocation of memory by malloc function*/
  int *arr=(int*)malloc(sizeof(int)*10);
  int i=0;

  if(arr!=NULL){
  /*When Successful Dynamic allocated memory */
    
    /*Assign data value*/
    for(i;i<10;i++){
      arr[i]=2*(i+1);
    }

    /*Print array elements*/
    for(i=0;i<10;i++){
      printf("\narr[%d] : %d",i,arr[i]);
    }

  }else{
    /*if arr pointer is NULL*/
    printf("\n Memory overflow");
  }
  /*Free arr elements*/
  free(arr);
  arr=NULL;
  return 0;

}

Output:

arr[0] : 2
arr[1] : 4
arr[2] : 6
arr[3] : 8
arr[4] : 10
arr[5] : 12
arr[6] : 14
arr[7] : 16
arr[8] : 18
arr[9] : 20

Note that programmer are responsible to create and free allocated memory of heap area. because there are program automatically not free of heap area memory. use free() function to remove that memory.

Function to create dynamic memory in c

C dynamic memory allocation Function

malloc ()

Malloc function are create dynamic memory of given number of bytes (8 bit 1 bytes). . This memory is present in heap area. malloc function are return the address of this dynamic created memory. malloc function syntax

data_type *pointer_var= (type_cast *) malloc(bytes)
Iteam Overview
data_type Predefined and user defined data type.
(type_cast *) malloc are return void type of pointer. so we need to type case in proper data type. they can accept both user defined and predefined data type.
bytes Given number of size of allocate dynamic memory.
Default value Garbage

For example:

int *data=(int *)malloc(sizeof(int)*5);

In this statement create an array of 5 integer and return this address.

Another example

char *data=(char *)malloc(sizeof(char)*15);

In this statement are create an array of 15 char and return first block of memory address.

important points : 1) malloc function are return first block of memory address. but assign this address to pointer variable first need to type-cast.
2) if in case malloc function are not create memory block of heap area. Then it will return NULL value.
3) Returning malloc function value. before use its will check it. if there are NULL. so we are not utilize this value. otherwise program will crash. most of case it will produce segmentation fault error.

Previously given an malloc function example. But also giving one more to understand the concept of dynamic memory allocation. View how to insert linked list node at beginning of linked list.

/*
 Example create linked list
*/

#include<stdio.h>
#include<stdlib.h>

/*structure of linked list*/
struct Node{

  int data;// linked list data 
  struct Node*next;// pointer field
};

/* Function declaration section here */
void insert(struct Node**root,int);
void show_data(struct Node*);
void remove_node(struct Node**root);

/*Help of this function create new linked list node. 
And there are inserted this element on end position of given linked list*/
void insert(struct Node**root,int value){

  /* create new memory block using malloc function. */
  struct Node*new_node=(struct Node*)malloc(sizeof(struct Node));

  /* check new create memory are allocate or not. */
  if(new_node){   
    /*Assign data and next pointer value to newly created node.*/
    new_node->data=value;
    new_node->next=*root;
    *root=new_node;

  }
  else{
    /* When malloc function not create memory block then. */
    printf("\n Memory overflow please try again..!");
  }
}


/* Help of this function showing all element of single linked list */
void show_data(struct Node*temp){

  if(temp==NULL){
      /*linked list are empty*/
    printf("Empty linked List\n");
  }
  else{
      /*When linked list are not empty*/
    while(temp){
          /*print linked list data*/
      printf("%d  ",temp->data);
          /*visit next node*/
      temp=temp->next;
    }
  }
}



/*Help of this function removing all linked list element.*/
void remove_node(struct Node**root){

  if(*root){
      /* temp pointed to root node */
    struct Node*temp=*root;

    while(temp){

          /*Moving root pointer to on next memory block.*/
      *root=temp->next;

          /*Before removing that linked node assign
            next pointer value are null.*/
      temp->next=NULL;

          /*Free linked list node element*/
      free(temp);

      temp=*root;
    }

    printf("\n");

  }
  else{
      /* When linked list is empty */
    printf("\n linked list is empty \n");
  }

}

int main(){
  /* Start program execution are here */

  struct Node*root=NULL;

  /* Assume that following data are inserted */

  /*1->2->3->4->5->NULL*/

  insert(&root,1);
  insert(&root,2);
  insert(&root,3);
  insert(&root,4);
  insert(&root,5);
  show_data(root);

  /*Removing linked list node*/
  remove_node(&root);

  /*end execution*/
  return 0;
}

Output:

5  4  3  2  1 
Create linked list node using malloc

help of pointer we are utilize of heap area memory. every linked list node create dynamically. and pointer field are connect are each to every node.

calloc()

Create dynamic memory of using calloc function. syntax of calloc function.

data_type * pointer_variable=(type_casting_pointer)calloc(number_of_element,data_size);

Explanation :
Data type : Predefined and user defined data type.
Pointer variable: Name of pointer variables.
Type casting: Modified address type cast.
Number of element: Number of element
Data size: Number of bytes.

calloc function are assign default value to memory location. there are zero for integer .Example

/* 
  Dynamic allocation of array using calloc
*/
/*Header file*/
#include <stdio.h>
#include <stdlib.h>

/*Global variables*/
int elements=5;
int main(){
  /*Entry point of program*/
  /*Dynamic allocation of memory by calloc function*/
  int *arr=(int*)calloc(elements,sizeof(int));
  int i=0;

  if(arr!=NULL){
  /*When Successful Dynamic allocated memory */
    
    /*Print array elements*/
    for(i=0;i<elements;i++){
      printf("\narr[%d] : %d",i,arr[i]);
    }

  }else{
    /*if arr pointer is NULL*/
    printf("\n Memory overflow");
  }
  /*Free arr elements*/
  free(arr);
  arr=NULL;
  return 0;

}
Example calloc function
arr[0] : 0
arr[1] : 0
arr[2] : 0
arr[3] : 0
arr[4] : 0

realloc:

help of realloc we are change the size of previously allocated memory of dynamically.

	data_type * pointer_variable=(type_casting_pointer)realloc(reallocate_pointer,new_size);

Example

/* 
  Example of Realloc function
*/
/*Header file*/
#include <stdio.h>
#include <stdlib.h>

/*Global variables*/
int elements=5;
int main(){
  /*Entry point of program*/
  /*Dynamic allocation of memory by calloc function*/
  int *arr=(int*)calloc(elements,sizeof(int)),
      *arr2=NULL;
  int i=0;

  if(arr!=NULL){
  /*When Successful Dynamic allocated memory */

    printf("\nBefore realloc");
    
    /*Print array elements*/
    for(i=0;i<elements;i++){
      printf("\narr[%d] : %d",i,arr[i]);
    }

    //realloced memory
    arr2=realloc(arr,sizeof(int)*(elements*2));
    if(arr2==NULL){
      printf( "Extended Memory Allocation Failed.");
      exit(1);
    }
    arr=arr2;

     for(i=0;i<elements*2;i++){
      arr[i]=i;//assign array elements
    }
    printf("\nAfter realloc");
    /*Print array elements*/
    for(i=0;i<elements*2;i++){
      printf("\narr[%d] : %d",i,arr[i]);
    }

  }else{
    /*if arr pointer is NULL*/
    printf("\n Memory overflow");
  }
  /*Free arr elements*/
  free(arr);
  arr=NULL;
  return 0;

}

Before realloc

Example Before realloc function

After realloc

Example After realloc

Output

Before realloc
arr[0] : 0
arr[1] : 0
arr[2] : 0
arr[3] : 0
arr[4] : 0
After realloc
arr[0] : 0
arr[1] : 1
arr[2] : 2
arr[3] : 3
arr[4] : 4
arr[5] : 5
arr[6] : 6
arr[7] : 7
arr[8] : 8
arr[9] : 9

free()

free is same name of its meaning. when we are not need heap area memory so we are free this memory. this function are accepted address of dynamic allocated memory. normally pointer are hold the address of heap area memory. so passign this pointer paramter in a free function.

Syntax

free(address_of_memory)

Example to create 2d dynamic array

/* 
  Example of free function
*/
/*Header file*/
#include <stdio.h>
#include <stdlib.h>

int main(){

  //three int pointers
  int *ptr[3],
      i=0,
      j=0;

  for(i;i<3;i++){
    //assign null value to pointer
    ptr[i]=NULL;
    //create dynamic memory of 4 integers
    ptr[i]=(int*)malloc(sizeof(int)*4);
    if(ptr[i]!=NULL){
      //assign array value
      for(j=0;j<4;j++){
        ptr[i][j]=i+j;
      }
    }else{
      printf("\n memory Overflow");
      exit(1);
    }

  }
  for(i=0;i<3;i++){
    printf("\n ptr[%d]",i);
    //print element
    for(j=0;j<4;j++){
      printf("\n ptr[%d][%d] : %d",i,j,ptr[i][j]);
    }
    free(ptr[i]);//free memory
    ptr[i]=NULL;
  }


}
2D Dynamic Array

When free(ptr[0])

free dynamic array

When free(ptr[1])

free dynamic array set-1

When free(ptr[2])

free dynamic array set-2

Output

 ptr[0]
 ptr[0][0] : 0
 ptr[0][1] : 1
 ptr[0][2] : 2
 ptr[0][3] : 3
 ptr[1]
 ptr[1][0] : 1
 ptr[1][1] : 2
 ptr[1][2] : 3
 ptr[1][3] : 4
 ptr[2]
 ptr[2][0] : 2
 ptr[2][1] : 3
 ptr[2][2] : 4
 ptr[2][3] : 5

© 2019, regularcodes.com, All rights reserved