SlideShare a Scribd company logo
1 of 37
Presentation
On
Memory Allocation
Memory Allocation
Memory allocation is an action of assigning the physical
or the virtual memory address space to a process (its
instructions and data). The two fundamental methods of
memory allocation are static and dynamic memory
allocation.
We have two types of memory allocation or we can say
two methods of binding, static and dynamic binding.
1. Static Memory Allocation
In static memory allocation, the size of the data required by
the process must be known before the execution of the
process initiates.
If the data sizes are not known before the execution of the
process, then they have to be guessed.
If the data size guessed is larger than the required, then it
leads to wastage of memory.
If the guessed size is smaller, then it leads to inappropriate
execution of the process.
As all the memory allocation operation required for the
process is done before the execution of the process has
started. So, it leads to faster execution of a process.
Static memory allocation provides more efficiency when
compared by the dynamic memory allocation.
2. Dynamic Memory Allocation
Dynamic Memory Allocation is a process in which we
allocate a block of memory during the run-time of a
program.
The actual size, of the data required, is known at the run
time so, it allocates the exact memory space to the
program thereby, reducing the memory wastage.
Dynamic memory allocation provides flexibility to the
execution of the program.
Advantages of Static Memory Allocation
Static memory allocation provides an efficient way of
assigning the memory to a process.
All the memory assigning operations are done before the
execution starts. So, there are no overheads of memory
allocation operations at the time of execution of the program.
Static memory allocation provides faster execution.
Advantages Dynamic Memory Allocation
Dynamic memory allocation provides a flexible way of
assigning the memory to a process.
Dynamic memory allocation reduces the
memory wastage as it assigns memory to a process during
the execution of that program. So, it is aware of the exact
memory size required by the program.
Disadvantages of static memory allocation
In static memory allocation, the system is unaware of the
memory requirement of the program. So, it has to guess
the memory required for the program.
Static memory allocation leads to memory wastage. As it
estimates the size of memory required by the program. So,
if the estimated size is larger, it will lead to
memory wastage else if the estimated size is smaller, then
the program will execute inappropriately.
Disadvantages of Dynamic Memory allocation
Dynamic memory allocation method has an overhead of
assigning the memory to a process during the time of its
execution.
Sometimes the memory allocation actions are repeated
several times during the execution of the program which
leads to more overheads.
The overheads of memory allocation at the time of its
execution slowdowns the execution to some extent.
Dynamic memory allocation is possible by 4 functions of
stdlib.h header file.
1.malloc()
2.calloc()
3.realloc()
4.free()
malloc() function
The malloc() function allocates single block of requested
memory.
It doesn't initialize memory at execution time, so it has garbage
value initially.
It returns NULL if memory is not sufficient
The syntax of malloc() function is given below
ptr=(cast-type*)malloc(byte-size)
calloc() function
The calloc() function allocates multiple block of requested
memory.
It initially initialize all bytes to zero.
It returns NULL if memory is not sufficient.
The syntax of calloc() function is given below:
ptr=(cast-type*)calloc(number, byte-size)
realloc() function
If memory is not sufficient for malloc() or calloc(), you can
reallocate the memory by realloc() function. In short, it
changes the memory size.
The syntax of realloc() function.
ptr=realloc(ptr, new-size)
free() function
The memory occupied by malloc() or calloc() functions must
be released by calling free() function. Otherwise, it will
consume memory until program exit.
The syntax of free() function.
free(ptr)
Array
Arrays are defined as the collection of similar type of data
items stored at contiguous memory locations.
Memory Allocation of the array
All the data elements of an array are stored at
contiguous locations in the main memory. The name of
the array represents the base address or the address of
first element in the main memory. Each element of the
array is represented by a proper indexing.
The indexing of the array can be defined in three
ways.
0 (zero - based indexing) : The first element of the array will
be arr[0].
1 (one - based indexing) : The first element of the array will
be arr[1].
n (n - based indexing) : The first element of the array can
reside at any random index number.
In the following image, we have shown the memory allocation
of an array arr of size 5. The array follows 0-based indexing
approach. The base address of the array is 100th byte. This will
be the address of arr[0]. Here, the size of int is 4 bytes
therefore each element will take 4 bytes in the memory.
Accessing Elements of an array
To access any random element of an array we need the
following information:
1.Base Address of the array.
2.Size of an element in bytes.
3.Which type of indexing, array follows.
Address of any element of a 1D array can be calculated by
using the following formula:
Byte address of element A[i] = base address + size * ( i -
first index)
Example :
In an array, A[10 ..... +2 ], Base address (BA) = 999, size of
an element = 2 bytes,
find the location of A[-1].
L(A[-1]) = 999 + [(-1) - (-10)] x 2
= 999 + 18
= 1017
2D Array
The 2D array is organized as matrices which can be represented
as the collection of rows and columns.
How to declare 2D Array
The syntax of declaring two dimensional array is very much
similar to that of a one dimensional array, given as follows.
int arr[max_rows][max_columns];
How do we access data in a 2D array
The elements of 2D arrays can be random accessed. Similar to
one dimensional arrays, we can access the individual cells in a
2D array by using the indices of the cells. There are two
indices attached to a particular cell, one is its row number
while the other is its column number.
However, we can store the value stored in any particular cell
of a 2D array to some variable x by using the following syntax.
int x = a[i][j];
Mapping 2D array to 1D array
A 3 X 3 two dimensional array is shown in the following image.
However, this array needs to be mapped to a one dimensional
array in order to store it into the memory.
There are two main techniques of storing 2D array elements
into memory
1. Row Major ordering
In row major ordering, all the rows of the 2D array are stored
into the memory contiguously. Considering the array shown in
the above image, its memory allocation according to row major
order is shown as follows
first, the 1st row of the array is stored into the memory
completely, then the 2nd row of the array is stored into the
memory completely and so on till the last row
2. Column Major ordering
According to the column major ordering, all the columns of
the 2D array are stored into the memory contiguously. The
memory allocation of the array which is shown in in the
above image is given as follows.
first, the 1st column of the array is stored into the memory
completely, then the 2nd row of the array is stored into the
memory completely and so on till the last column of the
array.
By Row Major Order
If array is declared by a[m][n] where m is the number of
rows while n is the number of columns, then address of an
element a[i][j] of the array stored in row major order is
calculated as,
Address(a[i][j]) = B. A. + (i * n + j) * size
where, B. A. is the base address or the address of the first
element of the array a[0][0] .
Calculating the Address of the random element of
a 2D array
By Column major order
If array is declared by a[m][n] where m is the number of
rows while n is the number of columns, then address of an
element a[i][j] of the array stored in row major order is
calculated as,
Address(a[i][j]) = ((j*m)+i)*Size + BA
where BA is the base address of the array.
STRUCTURE ALLOCATION
HOW STRUCTURE MEMBERS ARE STORED IN MEMORY?
Always, contiguous memory locations are used to store
structure members in memory. Consider below example to
understand how memory is allocated for structures.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <stdio.h>
#include <string.h>
struct student
{
int id1;
int id2;
char a;
char b;
float percentage;
};
int main()
{
int i;
struct student record1 = {1, 2, 'A', 'B', 90.5};
printf("size of structure in bytes : %dn",
sizeof(record1));
printf("nAddress of id1 = %u", &record1.id1 );
printf("nAddress of id2 = %u", &record1.id2 );
printf("nAddress of a = %u", &record1.a );
printf("nAddress of b = %u", &record1.b );
printf("nAddress of percentage = %u",&record1.percentage);
return 0;
}
Output
size of structure in bytes : 16
Address of id1 = 675376768
Address of id2 = 675376772
Address of a = 675376776
Address of b = 675376777
Address of percentage = 675376780
There are 5 members declared for structure in above program.
In 32 bit compiler, 4 bytes of memory is occupied by int
datatype. 1 byte of memory is occupied by char datatype and 4
bytes of memory is occupied by float datatype.
Please refer below table to know from where to where memory
is allocated for each datatype in contiguous (adjacent) location
in memory.
The pictorial representation of above structure memory
allocation is given below. This diagram will help you to
understand the memory allocation concept in C very easily
Common and Equivalence allocation
Lengthy argument lists in subroutines and user-defined
functions can occur as modularised programs grow
ever larger, requiring more and more information to be
passed between program units.
The COMMONblock, a piece of shared memory in the
computer, is another method for passing information
between program units.
Data stored in a COMMONblock is not passed
between program units via argument lists , but through
the COMMONstatement near the beginning of each
program unit.
There are two types of COMMON block:
blank and named.
A program may contain only one blank COMMONblock
but any number of named COMMONblocks.
Every COMMONblock must be declared in every program
unit in which the information stored therein is needed.
In addition, the unique blank COMMONblock must be
declared in the main program
Every subroutine or user-defined function that uses data stored in
the COMMON block , blank or named, must have a similar statement to
those above. The variable names do not need to match between
program units but it is vital that their types and the order in which they
appear in the list are identical.
Consider the following program fragment:
Example
PROGRAM MAIN
INTEGER A
REAL F,R,X,Y
COMMON R,A,F
A = -14
R = 99.9
F = 0.2
CALL SUB(X,Y)
… END
SUBROUTINE SUB(P,Q)
INTEGER I
REAL A,B,P,Q
COMMON A,I,B
… END
Main Program Common Memory
Storage
Subroutine
R 99.9 A
A -14 I
F 0.2 B
In this example, a blank COMMONblock holds three values:
a REALnumber, an INTEGERnumber, and another REALnumber.
Memory is shared in the COMMONblock in the following way:

More Related Content

What's hot (20)

Symbol table in compiler Design
Symbol table in compiler DesignSymbol table in compiler Design
Symbol table in compiler Design
 
Arrays
ArraysArrays
Arrays
 
Associative memory 14208
Associative memory 14208Associative memory 14208
Associative memory 14208
 
B and B+ tree
B and B+ treeB and B+ tree
B and B+ tree
 
2D Array
2D Array 2D Array
2D Array
 
sorting and its types
sorting and its typessorting and its types
sorting and its types
 
Circular queue
Circular queueCircular queue
Circular queue
 
Linked List
Linked ListLinked List
Linked List
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
 
Chapter 4 NumPy Basics Arrays and Vectorized Computation (Part I).pptx
Chapter 4 NumPy Basics Arrays and Vectorized Computation (Part I).pptxChapter 4 NumPy Basics Arrays and Vectorized Computation (Part I).pptx
Chapter 4 NumPy Basics Arrays and Vectorized Computation (Part I).pptx
 
Hashing in datastructure
Hashing in datastructureHashing in datastructure
Hashing in datastructure
 
stack presentation
stack presentationstack presentation
stack presentation
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
 
Sparse matrix and its representation data structure
Sparse matrix and its representation data structureSparse matrix and its representation data structure
Sparse matrix and its representation data structure
 
Infix to postfix conversion
Infix to postfix conversionInfix to postfix conversion
Infix to postfix conversion
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 
Queue ppt
Queue pptQueue ppt
Queue ppt
 
Introduction to data structure
Introduction to data structure Introduction to data structure
Introduction to data structure
 
Searching algorithms
Searching algorithmsSearching algorithms
Searching algorithms
 
sparse matrix in data structure
sparse matrix in data structuresparse matrix in data structure
sparse matrix in data structure
 

Similar to memory allocation by Novodita

Bsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structureBsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structureRai University
 
Bca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureBca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureRai University
 
Mca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureMca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureRai University
 
Chapter 1 - Introduction to Data Structure.ppt
Chapter 1 - Introduction to Data Structure.pptChapter 1 - Introduction to Data Structure.ppt
Chapter 1 - Introduction to Data Structure.pptNORSHADILAAHMADBADEL
 
Basic of array and data structure, data structure basics, array, address calc...
Basic of array and data structure, data structure basics, array, address calc...Basic of array and data structure, data structure basics, array, address calc...
Basic of array and data structure, data structure basics, array, address calc...nsitlokeshjain
 
UNIT-5_Array in c_part1.pptx
UNIT-5_Array in c_part1.pptxUNIT-5_Array in c_part1.pptx
UNIT-5_Array in c_part1.pptxsangeeta borde
 
data structure unit -1_170434dd7400.pptx
data structure unit -1_170434dd7400.pptxdata structure unit -1_170434dd7400.pptx
data structure unit -1_170434dd7400.pptxcoc7987515756
 
1. Data structures introduction
1. Data structures introduction1. Data structures introduction
1. Data structures introductionMandeep Singh
 
unit1Intro_final.pptx
unit1Intro_final.pptxunit1Intro_final.pptx
unit1Intro_final.pptxDEEPAK948083
 
data structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoredata structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoreambikavenkatesh2
 
VCE Unit 01 (2).pptx
VCE Unit 01 (2).pptxVCE Unit 01 (2).pptx
VCE Unit 01 (2).pptxskilljiolms
 

Similar to memory allocation by Novodita (20)

Unit 3
Unit 3 Unit 3
Unit 3
 
Bsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structureBsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structure
 
Bca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureBca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structure
 
Mca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureMca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structure
 
Chapter 1 - Introduction to Data Structure.ppt
Chapter 1 - Introduction to Data Structure.pptChapter 1 - Introduction to Data Structure.ppt
Chapter 1 - Introduction to Data Structure.ppt
 
Unit 3
Unit 3 Unit 3
Unit 3
 
Arrays
ArraysArrays
Arrays
 
arrays.docx
arrays.docxarrays.docx
arrays.docx
 
Basic of array and data structure, data structure basics, array, address calc...
Basic of array and data structure, data structure basics, array, address calc...Basic of array and data structure, data structure basics, array, address calc...
Basic of array and data structure, data structure basics, array, address calc...
 
UNIT-5_Array in c_part1.pptx
UNIT-5_Array in c_part1.pptxUNIT-5_Array in c_part1.pptx
UNIT-5_Array in c_part1.pptx
 
06 linked list
06 linked list06 linked list
06 linked list
 
data structure unit -1_170434dd7400.pptx
data structure unit -1_170434dd7400.pptxdata structure unit -1_170434dd7400.pptx
data structure unit -1_170434dd7400.pptx
 
1. Data structures introduction
1. Data structures introduction1. Data structures introduction
1. Data structures introduction
 
unit1Intro_final.pptx
unit1Intro_final.pptxunit1Intro_final.pptx
unit1Intro_final.pptx
 
data structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoredata structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysore
 
VCE Unit 01 (2).pptx
VCE Unit 01 (2).pptxVCE Unit 01 (2).pptx
VCE Unit 01 (2).pptx
 
Buffer overflow attack
Buffer overflow attackBuffer overflow attack
Buffer overflow attack
 
Ln liers
Ln liersLn liers
Ln liers
 
test1
test1test1
test1
 
Data structure
Data structureData structure
Data structure
 

Recently uploaded

Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 

Recently uploaded (20)

Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 

memory allocation by Novodita

  • 2. Memory Allocation Memory allocation is an action of assigning the physical or the virtual memory address space to a process (its instructions and data). The two fundamental methods of memory allocation are static and dynamic memory allocation. We have two types of memory allocation or we can say two methods of binding, static and dynamic binding.
  • 3. 1. Static Memory Allocation In static memory allocation, the size of the data required by the process must be known before the execution of the process initiates. If the data sizes are not known before the execution of the process, then they have to be guessed. If the data size guessed is larger than the required, then it leads to wastage of memory. If the guessed size is smaller, then it leads to inappropriate execution of the process.
  • 4. As all the memory allocation operation required for the process is done before the execution of the process has started. So, it leads to faster execution of a process. Static memory allocation provides more efficiency when compared by the dynamic memory allocation.
  • 5. 2. Dynamic Memory Allocation Dynamic Memory Allocation is a process in which we allocate a block of memory during the run-time of a program. The actual size, of the data required, is known at the run time so, it allocates the exact memory space to the program thereby, reducing the memory wastage. Dynamic memory allocation provides flexibility to the execution of the program.
  • 6. Advantages of Static Memory Allocation Static memory allocation provides an efficient way of assigning the memory to a process. All the memory assigning operations are done before the execution starts. So, there are no overheads of memory allocation operations at the time of execution of the program. Static memory allocation provides faster execution.
  • 7. Advantages Dynamic Memory Allocation Dynamic memory allocation provides a flexible way of assigning the memory to a process. Dynamic memory allocation reduces the memory wastage as it assigns memory to a process during the execution of that program. So, it is aware of the exact memory size required by the program.
  • 8. Disadvantages of static memory allocation In static memory allocation, the system is unaware of the memory requirement of the program. So, it has to guess the memory required for the program. Static memory allocation leads to memory wastage. As it estimates the size of memory required by the program. So, if the estimated size is larger, it will lead to memory wastage else if the estimated size is smaller, then the program will execute inappropriately.
  • 9. Disadvantages of Dynamic Memory allocation Dynamic memory allocation method has an overhead of assigning the memory to a process during the time of its execution. Sometimes the memory allocation actions are repeated several times during the execution of the program which leads to more overheads. The overheads of memory allocation at the time of its execution slowdowns the execution to some extent.
  • 10. Dynamic memory allocation is possible by 4 functions of stdlib.h header file. 1.malloc() 2.calloc() 3.realloc() 4.free() malloc() function The malloc() function allocates single block of requested memory. It doesn't initialize memory at execution time, so it has garbage value initially. It returns NULL if memory is not sufficient
  • 11. The syntax of malloc() function is given below ptr=(cast-type*)malloc(byte-size)
  • 12. calloc() function The calloc() function allocates multiple block of requested memory. It initially initialize all bytes to zero. It returns NULL if memory is not sufficient. The syntax of calloc() function is given below: ptr=(cast-type*)calloc(number, byte-size)
  • 13. realloc() function If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size. The syntax of realloc() function. ptr=realloc(ptr, new-size)
  • 14. free() function The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit. The syntax of free() function. free(ptr)
  • 15. Array Arrays are defined as the collection of similar type of data items stored at contiguous memory locations. Memory Allocation of the array All the data elements of an array are stored at contiguous locations in the main memory. The name of the array represents the base address or the address of first element in the main memory. Each element of the array is represented by a proper indexing.
  • 16. The indexing of the array can be defined in three ways. 0 (zero - based indexing) : The first element of the array will be arr[0]. 1 (one - based indexing) : The first element of the array will be arr[1]. n (n - based indexing) : The first element of the array can reside at any random index number.
  • 17. In the following image, we have shown the memory allocation of an array arr of size 5. The array follows 0-based indexing approach. The base address of the array is 100th byte. This will be the address of arr[0]. Here, the size of int is 4 bytes therefore each element will take 4 bytes in the memory.
  • 18. Accessing Elements of an array To access any random element of an array we need the following information: 1.Base Address of the array. 2.Size of an element in bytes. 3.Which type of indexing, array follows. Address of any element of a 1D array can be calculated by using the following formula: Byte address of element A[i] = base address + size * ( i - first index)
  • 19. Example : In an array, A[10 ..... +2 ], Base address (BA) = 999, size of an element = 2 bytes, find the location of A[-1]. L(A[-1]) = 999 + [(-1) - (-10)] x 2 = 999 + 18 = 1017
  • 20. 2D Array The 2D array is organized as matrices which can be represented as the collection of rows and columns. How to declare 2D Array The syntax of declaring two dimensional array is very much similar to that of a one dimensional array, given as follows. int arr[max_rows][max_columns];
  • 21. How do we access data in a 2D array The elements of 2D arrays can be random accessed. Similar to one dimensional arrays, we can access the individual cells in a 2D array by using the indices of the cells. There are two indices attached to a particular cell, one is its row number while the other is its column number. However, we can store the value stored in any particular cell of a 2D array to some variable x by using the following syntax. int x = a[i][j];
  • 22. Mapping 2D array to 1D array A 3 X 3 two dimensional array is shown in the following image. However, this array needs to be mapped to a one dimensional array in order to store it into the memory.
  • 23. There are two main techniques of storing 2D array elements into memory 1. Row Major ordering In row major ordering, all the rows of the 2D array are stored into the memory contiguously. Considering the array shown in the above image, its memory allocation according to row major order is shown as follows
  • 24. first, the 1st row of the array is stored into the memory completely, then the 2nd row of the array is stored into the memory completely and so on till the last row
  • 25. 2. Column Major ordering According to the column major ordering, all the columns of the 2D array are stored into the memory contiguously. The memory allocation of the array which is shown in in the above image is given as follows.
  • 26. first, the 1st column of the array is stored into the memory completely, then the 2nd row of the array is stored into the memory completely and so on till the last column of the array.
  • 27. By Row Major Order If array is declared by a[m][n] where m is the number of rows while n is the number of columns, then address of an element a[i][j] of the array stored in row major order is calculated as, Address(a[i][j]) = B. A. + (i * n + j) * size where, B. A. is the base address or the address of the first element of the array a[0][0] . Calculating the Address of the random element of a 2D array
  • 28. By Column major order If array is declared by a[m][n] where m is the number of rows while n is the number of columns, then address of an element a[i][j] of the array stored in row major order is calculated as, Address(a[i][j]) = ((j*m)+i)*Size + BA where BA is the base address of the array.
  • 29. STRUCTURE ALLOCATION HOW STRUCTURE MEMBERS ARE STORED IN MEMORY? Always, contiguous memory locations are used to store structure members in memory. Consider below example to understand how memory is allocated for structures.
  • 30. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 #include <stdio.h> #include <string.h> struct student { int id1; int id2; char a; char b; float percentage; }; int main() { int i; struct student record1 = {1, 2, 'A', 'B', 90.5}; printf("size of structure in bytes : %dn", sizeof(record1)); printf("nAddress of id1 = %u", &record1.id1 ); printf("nAddress of id2 = %u", &record1.id2 ); printf("nAddress of a = %u", &record1.a ); printf("nAddress of b = %u", &record1.b ); printf("nAddress of percentage = %u",&record1.percentage); return 0; }
  • 31. Output size of structure in bytes : 16 Address of id1 = 675376768 Address of id2 = 675376772 Address of a = 675376776 Address of b = 675376777 Address of percentage = 675376780 There are 5 members declared for structure in above program. In 32 bit compiler, 4 bytes of memory is occupied by int datatype. 1 byte of memory is occupied by char datatype and 4 bytes of memory is occupied by float datatype. Please refer below table to know from where to where memory is allocated for each datatype in contiguous (adjacent) location in memory.
  • 32.
  • 33. The pictorial representation of above structure memory allocation is given below. This diagram will help you to understand the memory allocation concept in C very easily
  • 34. Common and Equivalence allocation Lengthy argument lists in subroutines and user-defined functions can occur as modularised programs grow ever larger, requiring more and more information to be passed between program units. The COMMONblock, a piece of shared memory in the computer, is another method for passing information between program units. Data stored in a COMMONblock is not passed between program units via argument lists , but through the COMMONstatement near the beginning of each program unit.
  • 35. There are two types of COMMON block: blank and named. A program may contain only one blank COMMONblock but any number of named COMMONblocks. Every COMMONblock must be declared in every program unit in which the information stored therein is needed. In addition, the unique blank COMMONblock must be declared in the main program
  • 36. Every subroutine or user-defined function that uses data stored in the COMMON block , blank or named, must have a similar statement to those above. The variable names do not need to match between program units but it is vital that their types and the order in which they appear in the list are identical. Consider the following program fragment: Example PROGRAM MAIN INTEGER A REAL F,R,X,Y COMMON R,A,F A = -14 R = 99.9 F = 0.2 CALL SUB(X,Y) … END SUBROUTINE SUB(P,Q) INTEGER I REAL A,B,P,Q COMMON A,I,B … END
  • 37. Main Program Common Memory Storage Subroutine R 99.9 A A -14 I F 0.2 B In this example, a blank COMMONblock holds three values: a REALnumber, an INTEGERnumber, and another REALnumber. Memory is shared in the COMMONblock in the following way: