Search This Blog

Showing posts with label list. Show all posts
Showing posts with label list. Show all posts

Dynamic Memory Allocation in C - Explanation With Examples

In static memory allocation, we know how much memory (bytes) is going to be used before execution of the program. Dynamic memory allocation is essential where the amount of memory the needed by the program depends on the input of the user or any other input obtained during execution time. That is why it is called dynamic memory allocation.

Consider an example of students progress report (for the sake of simplicity). The number of students are different in different classes. There fore, we have to read the number of students from the user (data entry operator). For each student, we need an integer for register number, a few integers to store scores in subjects, a few characters to store address and so on. In this case, the total amount of memory needed depends on the number of students in a class. There fore, the amount of memory that should be allocated for the program should be decided based on the input. In such cases we use dynamic memory allocation.

C programming language allows dynamic memory allocation. Most of modern programming languages use dynamic memory allocation. Java is an example. Unlike C, there is not a concept of pointers in Java because all variables are actually pointers.

Functions for Dynamic Memory Allocation in C

The functions used for dynamic memory allocation or deallocation are malloc, realloc, calloc and free. These functions are defined in the header file stdlib.h
malloc
This function is used to allocated specified number of bytes.
realloc
Used to increase or decrease size of a block of memory. Allocation or Deallocation of bytes is performed if necessary.
calloc
Allocates specified number of bytes and also intialises all bytes to zero. This function allows to specify how many blocks of specified size should be allocated.
free
Deallocates and releases the specified block of memory.
We shall see each function with examples.

Malloc function

First, we will see the syntax of malloc function. Then it will be easier to explain. Syntax is as follows:

void * malloc(int sizeInBytes);

The above shown prototype of malloc function tells that it always return a pointer to 'void' data type. That is, the pointer can be type-casted to int pointer, char pointer or to any other data type. malloc functions takes a parameter which is the amount of memory (number of bytes) to be allocated. It is recommended to specify the size using sizeof operator. We will see a few examples of dynamic memory allocation using malloc function.

int *p=malloc(10*sizeof(char));
Allocates memory to accommodate 10 characters.
int *p=malloc(20*sizeof(int));
Allocates memory to accommodate 20 integers.
int *p=malloc(sizeof(float));
Allocates memory to accommodate a float.
int *p=malloc(10*sizeof(struct student));
Allocates memory to accommodate 10 instances of structure named student. This is how to store derived datatypes (user defined data types) like structures dynamically in c.

Realloc Function

Realloc function is used either to shrink or to expand an already allocated memory. It is called after allocation of memory using malloc or calloc function. Suppose we initially allocated memory for 10000 characters dynamically. Later, during the of execution of program, we find that only 5000 characters need to be stored. Therefore, we are not going to use the rest. To avoid memory wastage, we may deallocate the remaining 5000 character spaces trailing being the used 5000. The following code will shrink the initially allocated 10000 chars to 5000 chars by deallocating the remaining.

void * realloc(void *pointer,size_t size)

The first parameter pointer is the pointer to the memory block allocated earlier. The next argument size is the new (updated) size. It size is greater than the older size, additional memory will be allocated to get size number of bytes allocated in total. If it is less than older size, a part of memory will be deallocated which is equal to the difference between initial size and new size. If first parameter is NULL, a fresh block with specified size will be allocated.

char *ptr;
//Initial allocation
ptr = (char *) malloc(150);

//Reallocating memory to 50 char
ptr = (char *) realloc(ptr, 50);

Calloc Function

Calloc function is not much significantly different from malloc. The differences between malloc and calloc are:

  • Calloc lets you to specify the number of variables (of same data type) and space needed by each data type by taking two parameters.
  • When allocated using malloc, the memory block may contain junk data (garbage values) but calloc initializes every allocated byte to zero.
The following code fragment shows example use of calloc with structure:

#include<stdlib.h>
struct student
{
int rollno;
char name[30];
};

int main()
{
struct student *list,*temp;
list=(struct student *)calloc(5,sizeof(struct student));
for(temp=list;temp-list<5;temp++)
    {
    printf("Enter roll number and name of student\n");
    scanf("%d%s",&temp->rollno,&temp->name);
    }
printf("\nThe students are:\n");
for(temp=list;temp-list<5;temp++)
    {
    printf("Roll number: %d  Name: %s\n",temp->rollno,temp->name);
    }
free(list);
return 0;
}
Output
Enter roll number and name of student
1
matthew
Enter roll number and name of student
2
mathews
Enter roll number and name of student
3
shareef
Enter roll number and name of student
4
muneer
Enter roll number and name of student
5
nihal

The students are:
Roll number: 1  Name: matthew
Roll number: 2  Name: mathews
Roll number: 3  Name: shareef
Roll number: 4  Name: muneer
Roll number: 5  Name: nihal

In the above example a structure named student is used. Each structure variable has a roll number and name. Memory to store for 5 student structure variables are allocated using calloc. The pointer arithmetic for pointers to structures is also demonstrated in above program.

Free Function

The free function is used to free (deallocate) an already allocated block of memory. When your program no longer needs the dynamically allocated block of memory, the free function should be called to return the memory occupied to the free store. In the above example program, the following line of code deallocated the allocated block of memory.

free(list);

The free function takes the pointer to the block of memory which is allocated dynamically as parameter and frees or deallocates the block so that it can be used later.

C Program to Simulate the ls Command in Linux Operating system

This is a c program to do Simulation of ls Command in linux. The ls command lists all the contents of the directory including filse and sub-directories. The following c program in simulates the ls command.
#include<stdio.h>
#include<dirent.h>
main()
{
char dirname[10];
DIR*p;
struct dirent *d;
printf("Enter directory name\n");
scanf("%s",dirname);
p=opendir(dirname);
if(p==NULL)
  {
  perror("Cannot find directory");
  exit(-1);
  }
while(d=readdir(p))
  printf("%s\n",d->d_name);
}

Related Posts:

C Program to Simulate ls Command in Linux
C Program to Simulate Round Robin CPU Scheduling Algorithm
C Program to Simulate Priority CPU Scheduling Algorithm
C Program to Simulate First Come First Serve (FCFS) CPU Scheduling Algorithm
C Program to Simulate rmdir Command or Delete Directory
C Program to Open, Read and Write Files
C Program to Create Process and Display Process ID - OS Lab Program
How to Use Fork and Exec System Calls
How to Use Exit System Call
C Program to make Parent Process Wait for Child to Terminate
C Program to Simulate GREP Command in Linux
C Program to make Child Process an Orphan Process
C Program to Show Process ID in Linux
C Program for Inter Process Communication using Pipes or Named Pipes (Chat Program)
C Program to Create a Process Using Fork System Call

C Program To Implement Circular Linked List

C Program to implement circular linked list.

c program to implement circular linked list c or c++ program source code for linked list implementation with example



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

struct node
{
int info;
struct node *link;
}*last;
void create_list(int num);
void addatbeg(int num);
void addafter(int num,int pos);
void del(int num);
void display();
void main()
{
int choice,n,m,po,i;
last=NULL;
while(1)
{
printf("1.Create List\n");
printf("2.Add at begining\n");
printf("3.Add after \n");
printf("4.Delete\n");

printf("5.Display\n");
printf("6.Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);

switch(choice)
{
case 1: printf("How many nodes you want : ");
scanf("%d",&n);
for(i=0; i < n;i++)
{
printf("Enter the element : ");
scanf("%d",&m);
create_list(m);
}
break;
case 2: printf("Enter the element : ");
scanf("%d",&m);
addatbeg(m);
break;
case 3: printf("Enter the element : ");
scanf("%d",&m);
printf("nter the position after which this element is inserted: ");
scanf("%d",&po);
addafter(m,po);
break;
case 4: if(last == NULL)
{
printf("List underflow\n");
continue;
}
printf("Enter the number for deletion : ");
scanf("%d",&m);
del(m);
break;
case 5: display();
break;
case 6: exit(0);
default:printf("Wrong choice\n");
}
}
}
void create_list(int num)
{
struct node *temp;
temp=(node*)malloc(sizeof(struct node));
temp->info = num;
if(last == NULL)
{
last = temp;
temp->link = last;
}
else
{
temp->link = last->link;
last->link = temp;
last = temp;
}
}

void addatbeg(int num)
{
struct node *temp;
temp =(node*)malloc(sizeof(struct node));
temp->info = num;
temp->link = last->link;
last->link = temp;
}
void addafter(int num,int pos)
{
struct node
*temp,*q;
int i;
q = last->link;
for(i=0;i<pos-1;i++)
{
q = q->link;
if(q==last->link)
{
printf("There are less than %d elements\n",pos);
return;
}
}
temp =(node*)malloc(sizeof(struct node) );
temp->link = q->link;
temp->info = num;
q->link = temp;
if(q==last) //Element inserted at the end
last=temp;
}//End of addafter()

void del(int num)
{
struct node *temp,*q;
if( last->link == last && last->info == num) //Only one element
{
temp=last;
last = NULL;
free(temp);
return;
}
q = last->link;
if(q->info == num)
{
temp = q;
last->link = q->link;
free(temp);
return;
}
while(q->link !=last)
{
if(q->link->info==num) //Element deleted in between
{
temp = q->link;
q->link = temp->link;
free(temp);
printf("%d deleted\n",num);
return;
}
q = q->link;
}
if(q->link->info==num) //Last element deleted q->link=last
{
temp = q->link;
q->link = last->link;
free(temp);
last = q;
return;
}
printf("Element %d not found\n",num);
}

void display()
{
struct node *q;
if(last == NULL)
{
printf("List is empty\n");
return;
}
q = last->link;
printf("List is :\n");
while(q != last)
{
printf("%d ", q->info);
q = q->link;
}
printf("%d\n",last->info);
}