Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 24

SUBJECT CODE

TYPE THE SUBJECT NAME HERE

UNIT NO. 5
STRUCTURES AND FILE PROCESSING

5.4 Dynamic memory allocation-Singly linked list-


typedef
I I

20ESCS101
Problem Solving and Programming in C
(Common to ALL Departments)
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Dynamic Memory Allocation

Dynamic Memory Allocation: Ability of a program to use more memory space at execution time
❖ Memory space required can be specified at the time of execution.
❖ C supports allocating and freeing memory dynamically using library routines.
❖ Hold new nodes -Use function malloc to allocate memory.
❖ Release space no longer needed -Use function free to deallocate memory
❖ Use #include <stdlib.h> header file when using malloc & free functions.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Reasons of allocating memory dynamically:

❖ When we do not know how much amount of memory would be needed for the program
beforehand.
❖ When we want data structures without any upper limit of memory space.
❖ When we want to use our memory space more efficiently.Example: If we have allocated
memory space for a 1D array as array[20] and you end up using only 10 memory spaces
then the remaining 10 memory spaces would be wasted and this wasted memory cannot
even be utilized by other program variables.
❖ Dynamically created lists insertions and deletions can be done very easily just by the
manipulation of addresses whereas in case of statically allocated memory insertions and
deletions lead to more movements and wastage of memory.
❖ When we want you to use the concept of structures and linked list in programming,
dynamic memory allocation is a must.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Memory Allocation Process

❖ Variable memory is allocated in three areas: • Global data section • Run-time


stack • Dynamically allocated - heap.
❖ Global variables are allocated in the global data section and are accessible from
all parts of the program.
❖ Local variables are allocated during execution on the run-time stack. Dynamically
allocated variables are items created during run-time and are allocated on the
heap.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Memory Allocation Functions

❖ malloc() – Allocates requested number of bytes and returns a pointer to the first byte
of the allocated space.
❖ calloc()– Allocates space for an array of elements, initializes them to zero and then
returns a pointer to the memory.
❖ free() Frees previously allocated space.
❖ realloc()– Modifies the size of previously allocated space.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Malloc()

The name "malloc" stands for memory allocation.This function reserves a block of memory of the
specified number of bytes , its declaration is void*malloc(size);

malloc () returns the pointer to the 1st byte and allocate memory, and its return type is void,
which can be type casted as: int *p=(datatype*)malloc(size).

If memory allocation is successful, it returns the address of the memory chunk that was allocated
and it returns null on unsuccessful allocation .Example: int*p=(int*)malloc(10);
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Calloc()
calloc” or “contiguous allocation” method in C is used to dynamically allocate the
specified number of blocks of memory of the specified type. It initializes each block with a
default value ‘0’.
Syntax:
ptr = (cast-type*)calloc(n, element-size);
For Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements each with the size of
the float.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Free()
“free” method in C is used to dynamically de-allocate the memory. The memory allocated
using functions malloc() and calloc() is not de-allocated on their own. Hence the free()
method is used, whenever the dynamic memory allocation takes place. It helps to reduce
wastage of memory by freeing it.
Syntax: free(ptr);
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Realloc()

“realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a


previously allocated memory. In other words, if the memory previously allocated with the help of
malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory. re-
allocation of memory maintains the already present value and new blocks will be initialized with
default garbage value.
Syntax:
ptr = realloc(ptr, newSize); where ptr is reallocated with new size 'newSize'.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Advantages of Dynamic memory allocation

• Data structures can grow and shrink according to the requirement.

• We can allocate (create) additional storage whenever we need them.

• We can deallocate (free/delete) dynamic space whenever we're done with


them.

• Dynamic Allocation is done at run time.

Disadvantages of Dynamic memory allocation

• As the memory is allocated during runtime, it requires more time.

• Memory needs to be freed by the user when done.This is important as it is


more likely to turn into bugs that are difficult to find.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Typedef

❖ typedef is a keyword used in C language to assign alternative names to existing data types.
❖ It's mostly used with user defined datatypes, when names of the datatypes become
slightly complicated to use in programs.
❖ General syntax for using typedef: typedef <existing_name> <alias_name>
❖ Following is an example to define a term BYTE for one-byte numbers –

typedef unsigned char BYTE;

❖ After this type definition, the identifier BYTE can be used as an abbreviation for the type
unsigned char, for example.. BYTE b1, b2;
❖ By convention, uppercase letters are used for these definitions to remind the user that the
type name is really a symbolic abbreviation, but we can use lowercase, as follows − typedef
unsigned char byte;
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

❖ Application of typedef -It can be used to give a name to user defined data type as
well.

For example:

typedef struct

{ type member1;

type member2;

type member3;

} type_name;

Here type_name represents the structure definition associated with it. Now this
type_name can be used to declare a variable of this structure type.type_name t1, t2;
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Structure definition using typedef

❖ We can use typedef to give a name to your user defined data types as well. For example,
we can use typedef with structure to define a new data type and then use that data type to
define structure variables directly as follows –

#include<stdio.h>

#include<string.h>

typedef struct employee

char name[50];

int salary;

}emp;
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

void main( )

emp e1;

printf("\nEnter Employee record:\n");

printf("\nEmployee name:\t");

scanf("%s", e1.name);

printf("\nEnter Employee salary: \t");

scanf("%d", &e1.salary);

printf("\nstudent name is %s", e1.name);

printf("\nroll is %d", e1.salary); }


20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

typedef and Pointers


❖ typedef can be used to give an alias name to pointers also. Here we have a case
in which use of typedef is beneficial during pointer declaration.
❖ In Pointers * binds to the right and not on the left.

int* x, y;

❖ By this declaration statement, we are actually declaring x as a pointer of type int,


whereas y will be declared as a plain int variable.

typedef int* IntPtr;

IntPtr x, y, z;

❖ But if we use typedef like we have used in the example above, we can declare
any number of pointers in a single statement.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

typedef vs #define
❖ #define is a C-directive which is also used to define the aliases for various data types
similar to typedef but with the following differences −
❏ typedef is limited to giving symbolic names to types only whereas #define can be used
to define alias for values as well, q.,we can define 1 as ONE etc.
❏ typedef interpretation is performed by the compiler whereas #define statements are
processed by the pre-processor.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

LINKED LIST

Linked List is a linear data structure. Unlike arrays, linked list elements are not stored

at a contiguous location; the elements are linked using pointers.

Linked List Representation

● Link − Each link of a linked list can store a data called an element.
● Next − Each link of a linked list contains a link to the next link called Next.
● LinkedList − A Linked List contains the connection link to the first link called First.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Limitation of arrays

Arrays can be used to store linear data of similar types, but arrays have the following limitations.

1) The size of the arrays is fixed: So we must know the upper limit on the number of

elements in advance. Also, generally, the allocated memory is equal to the upper limit

irrespective of the usage.

2) Inserting a new element in an array of elements is expensive because the room has to be

created for the new elements and to create room existing elements have to be shifted.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Types of Linked List

Following are the various types of linked list.

● Singly Linked List − Item navigation is forward only.


● Doubly Linked List − Items can be navigated forward and backward.
● Circular Linked List − Last item contains link of the first element as next and the

first element has a link to the last element as previous.

Basic Operations

Following are the basic operations supported by a list.

● Insertion
○ Adds an element at the beginning of the list.
○ Adds an element at the middle of the list.
○ Adds an element at the end of the list.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

● Deletion
○ Deletes an element at the beginning of the list.
○ Deletes an element at the middle of the list
○ Deletes an element at the end of the list
● Display − Displays the complete list.
● Search − Searches an element using the given key.

Singly Linked List


Single linked list is a sequence of elements in which every element has a link to its next
element in the sequence.The first node is called the head; it points to the first node of the
list and helps us access every other element in the list. The last node, also sometimes
called the tail, points to NULL which helps us in determining when the list ends.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

int main()
Sample Program-Singly Linked list
#include <stdio.h> {int n,num,pos;

#include <stdlib.h> printf("\n\n Linked List : Delete first node of Singly


Linked List :\n");
struct node
printf("---------------------------------------------------------
{ int num; //Data of the ---\n");
node
printf(" Input the number of nodes : ");
struct node *nextptr; //Address of the node
scanf("%d", &n);
}*stnode;
createNodeList(n);
void createNodeList(int n); //function to
create the list printf("\n Data entered in the list are : \n");
displayList();
void FirstNodeDeletion(); //function to
delete the first node FirstNodeDeletion();

void displayList(); //function to printf("\n Data, after deletion of first node : \n");
display the list
displayList();

return 0; }
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

void createNodeList(int n) tmp = stnode;

{ struct node *fnNode, *tmp; for(i=2; i<=n; i++)

int num, i; {fnNode = (struct node *)malloc(sizeof(struct node));

stnode = (struct node *)malloc(sizeof(struct if(fnNode == NULL)


node));
{printf(" Memory can not be allocated.");
if(stnode == NULL)
break; }

else
{ printf(" Memory can not be
allocated."); { printf(" Input data for node %d : ", i);

} scanf(" %d", &num);

else fnNode->num = num;


fnNode->nextptr = NULL;
{
tmp->nextptr = fnNode;
printf(" Input data for node 1 : ");
tmp = tmp->nextptr;
scanf("%d", &num);
}
stnode-> num = num;
} } }
stnode-> nextptr = NULL;
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

void FirstNodeDeletion() void displayList()

{ struct node *toDelptr; { struct node *tmp;

if(stnode == NULL) if(stnode == NULL)

{ {

printf(" There are no node in the list."); printf(" No data found in the list.");

} }

else else

{ { tmp = stnode;

toDelptr = stnode; while(tmp != NULL)

stnode = stnode->nextptr; {

printf("\n Data of node 1 which is being deleted is : printf(" Data = %d\n", tmp->num);
%d\n", toDelptr->num);
tmp = tmp->nextptr; }
free(toDelptr); } }
}

}
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Video link

1. https://www.youtube.com/watch?v=udfbq4M2Kfc
2. https://www.youtube.com/watch?v=HrY_YmU1vdg

You might also like