Вы находитесь на странице: 1из 5

#18 Dynamic Memory Allocation

C Notes Vol-3 by Saurabh Shukla


www.mysirg.com

#18 Dynamic Memory Allocations


By Saurabh Shukla | 2017mysirg.com

DMA: Dynamic Memory Allocation

To store data we create variables in our program. This can be done by using data types.

In all our previous programs we wrote data type declaration instruction to specify variables to
the compiler. Compiler resolve declaration statements at compile time and maintain variable
related information in symbol table.

The amount of memory allocated for variables depend upon the information created by
compiler at compile time by looking at declaration statements. This is called static memory
allocation.

The benefit of static memory allocation is its cost effectiveness in terms of time. Since decision
about amount of memory needed for variables are already done at compile time, no extra time
would be consumed for this purpose at the time of execution

The major disadvantage of static memory allocation is lack of flexibility in memory consumption.
Since the decision regarding amount of memory has already been taken at compile time no
change could be made during run time.

There are scenarios where programmer is not sure about the amount of data to be handled by
the program. Static memory allocation is definitely a bad choice in such case. Solution to this
problem is dynamic memory allocation.

Decision of allocating memory to store data has taken at run time gives flexibility to the
programmer to make program efficient and cost effective in terms of memory consumption

Allocating memory at run time can be done by using either of two predefined functions:

1) malloc()

2) calloc()

We can also de-allocate memory using a predefined function free(). This function can release
memory that has been allocated previously by either malloc() or calloc() function

There are subtle differences between static memory allocation and dynamic memory allocation.
Memory blocks created by malloc() or calloc() has no name but can only be access using their
addresses
#18 Dynamic Memory Allocation
C Notes Vol-3 by Saurabh Shukla
www.mysirg.com

Function malloc()

The malloc() function allocates a block of memory in bytes. The malloc() function is like a
request to the RAM of the system to allocate memory, if the request is granted, returns a
pointer to the first block. However if it fails to allocate memory returns NULL.

The malloc() function reserves a block of memory of specified size and returns a pointer of type
void.

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

Function calloc()

The calloc() function is used for requesting memory space at run time for storing derived data
types such as arrays and structures. While malloc() allocates a single block of storage space,
calloc() allocates multiple blocks of storage, each of same size, and then sets all bytes to zero.

ptr = (cast type*)calloc(n, element size);

This statement allocates contiguous space for n blocks each of size element size bytes. All bytes
are initialized to zero and pointer to the first byte of the allocated region is returned. If not
enough space NULL is returned

Function free()

The free function is used to de-allocate the previously allocated memory using malloc or calloc
functions.

free(ptr);

Simple linked list program to understand the usage of DMA:

Write a program to prepare a list of integers and manage basic operations on it like adding
new data to the list and deleting old data from the list.

#include<conio.h>
#include<stdio.h>
#include<alloc.h>
#include<stdlib.h>
struct node
{
int x;
struct node *p;
};
struct node *START=NULL;
void adddata();
#18 Dynamic Memory Allocation
C Notes Vol-3 by Saurabh Shukla
www.mysirg.com

void viewlist();
void deletedata();
int main()
{
int ch;
while(1)
{
clrscr();
printf(\n1. Add data to list);
printf(\n2. View list);
printf(\n3. Delete data from list);
printf(\n4. Exit);
printf(\n\nEnter your choice);
scanf(%d,&ch);
switch(ch)
{
case 1:
adddata();
break;
case 2:
viewlist();
break;
case 3:
deletedata();
break;
case 4:
exit(0);
default:
printf(Invalid Choice);
}
getch();
}
return(0);
}
void adddata()
{
struct node *n,*t;
n=(struct node*)malloc(sizeof(struct node));
printf(Enter a number: );
scanf(%d,&n->x);
n->p=NULL;
if(START==NULL)
START=n;
else
{
t=START;
while(t->p!=NULL)
#18 Dynamic Memory Allocation
C Notes Vol-3 by Saurabh Shukla
www.mysirg.com

t=t->p;
t->p=n;
}
}
void viewlist()
{
struct node *t;
if(START==NULL)
printf(List is empty);
else
{
t=START;
while(t!=NULL)
{
printf( %d ,t->x);
t=t->p;
}
}
}
void deletedata()
{
struct node *r;
r=START;
if(START==NULL)
printf(List is empty);
else
{
START=r->p;
free(r);
}
}
Program to input string of any length

int main()
{
char ch,*p,*temp=0;
int i=0,size=0;
clrscr();
printf("Enter a string:\n");
p=(char*)calloc(size+1,sizeof(char));
while(1)
{
ch=getch();
if(ch==13)
break;
if(ch==8)
continue;
#18 Dynamic Memory Allocation
C Notes Vol-3 by Saurabh Shukla
www.mysirg.com

printf("%c",ch);
*(p+i)=ch;
free(temp);
temp=(char*)calloc(size+2,sizeof(char));
for(i=0;i<=size;i++)
{
*(temp+i)=*(p+i);
}
*(temp+i)='\0';
free(p);
size++;
p=(char*)calloc(size+1,sizeof(char));
i=0;
while(*(temp+i)!='\0')
{
*(p+i)=*(temp+i);
i++;
}

printf("You have entered: %s",temp);


printf("\nLength of string is %d",strlen(temp));
getch();
return(0);
}

References:

YouTube video links

Lecture 18 Dynamic Memory Allocation in C part-1


o https://youtu.be/ZSzzY3adfDM?list=PL7ersPsTyYt2Q-SqZxTA1D-melSfqBRMW
Lecture 18 Dynamic Memory Allocation in C part-2
o https://youtu.be/nd7WJ4Q9gog?list=PL7ersPsTyYt2Q-SqZxTA1D-melSfqBRMW

Exercise

1) Write a program to implement singly linked.


2) Write a program to implement stack using linked list.
3) Write a program to implement doubly linked list.
4) Write a program to input any number of strings and arrange them in dictionary order.
5) Write a program to sort an array of any number of elements.

Вам также может понравиться