SlideShare a Scribd company logo
Dynamic Memory
Allocation
Submitted to:
Anupam Shrama
Assistant Professor ,CSE
Submitted by: (GROUP-14)
SUNNY CHAKRABORTY-1915132
SUDHIR-1915131
SHIVANSHU-1915125
1
2
Problem with Arrays
 Sometimes
Amount of data cannot be predicted beforehand
Number of data items keeps changing during
program execution
 Example: Seach for an element in an array of N
elements
 One solution: find the maximum possible value of N
and allocate an array of N elements
Wasteful of memory space, as N may be much
smaller in some executions
Example: maximum value of N may be 10,000, but a
particular run may need to search only among 100
elements
Using array of size 10,000 always wastes memory
in most cases
Better Solution
Dynamic memory allocation
Know how much memory is needed after the
program is run
Example: ask the user to enter from keyboard
Dynamically allocate only the amount of memory
needed
C provides functions to dynamically allocate
memory
malloc, calloc, realloc
3
4
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.
 We will only do malloc and free
5
Allocating a Block of Memory
A block of memory can be allocated using the
function malloc
 Reserves a block of memory of specified size and returns a pointer of type void
 The return pointer can be type-casted to any pointer type
General format:
type *p;
p = (type *) malloc (byte_size);
6
Example
p = (int *) malloc(100 * sizeof(int));
 A memory space equivalent to 100 times the size of an int
bytes is reserved
 The address of the first byte of the allocated memory is
assigned to the pointer p of type int
p
400 bytes of space
7
Contd.
 cptr = (char *) malloc (20);
Allocates 20 bytes of space for the pointer cptr of type char
 sptr = (struct stud *) malloc(10*sizeof(struct
stud));
Allocates space for a structure array of 10 elements. sptr points
to a structure element of type struct stud
Always use sizeof operator to find number of bytes for a
data type, as it can vary from machine to machine
8
Points to Note
 malloc always allocates a block of contiguous bytes
 The allocation can fail if sufficient contiguous memory
space is not available
 If it fails, malloc returns NULL
if ((p = (int *) malloc(100 * sizeof(int))) == NULL)
{
printf (“n Memory cannot be allocated”);
exit();
}
Using the malloc’d Array
 Once the memory is allocated, it can be used with
pointers, or with array notation
 Example:
int *p, n, i;
scanf(“%d”, &n);
p = (int *) malloc (n * sizeof(int));
for (i=0; i<n; ++i)
scanf(“%d”, &p[i]);
The n integers allocated can be accessed as *p, *(p+1),
*(p+2),…, *(p+n-1) or just as p[0], p[1], p[2], …,p[n-1]
9
10
Example
printf("Input heights for %d
students n",N);
for (i=0; i<N; i++)
scanf ("%f", &height[i]);
for(i=0;i<N;i++)
sum += height[i];
avg = sum / (float) N;
printf("Average height = %f
n",
avg);
free (height);
return 0;
}
int main()
{
int i,N;
float *height;
float sum=0,avg;
printf("Input no. of
studentsn");
scanf("%d", &N);
height = (float *)
malloc(N *
sizeof(float));
malloc( )-ing array of structures
11
typedef struct{
char name[20];
int roll;
float SGPA[8], CGPA;
} person;
void main()
{
person *student;
int i,j,n;
scanf("%d", &n);
student = (person *)malloc(n*sizeof(person));
for (i=0; i<n; i++) {
scanf("%s", student[i].name);
scanf("%d", &student[i].roll);
for(j=0;j<8;j++) scanf("%f", &student[i].SGPA[j]);
scanf("%f", &student[i].CGPA);
}
}
Dynamic Arrays of pointers
12
int main()
{
char word[20], **w; /* “**w” is a pointer to a pointer array */
int i, n;
scanf("%d",&n);
w = (char **) malloc (n * sizeof(char *));
for (i=0; i<n; ++i) {
scanf("%s", word);
w[i] = (char *) malloc ((strlen(word)+1)*sizeof(char));
strcpy (w[i], word) ;
}
for (i=0; i<n; i++) printf("w[%d] = %s n",i, w[i]);
return 0;
}
5
India
Australia
Kenya
NewZealand
SriLanka
w[0] = India
w[1] = Australia
w[2] = Kenya
w[3] = NewZealand
w[4] = SriLanka
Output
How this will look like
13
w 0
1
2
3
4
I n d i a 0
S r i L a n k a 0
A u s t r a l I a 0
K e n y a 0
N e w Z e a l a n d 0
free()14
The C library function void free(void *ptr) deallocates the memory
previously allocated by a call to calloc, malloc, or realloc.
15

More Related Content

What's hot

Dma
DmaDma
The TensorFlow dance craze
The TensorFlow dance crazeThe TensorFlow dance craze
The TensorFlow dance craze
Gabriel Hamilton
 
String Manipulation Function and Header File Functions
String Manipulation Function and Header File FunctionsString Manipulation Function and Header File Functions
Function recap
Function recapFunction recap
Function recapalish sha
 
Matlab Nn Intro
Matlab Nn IntroMatlab Nn Intro
Matlab Nn Intro
Imthias Ahamed
 
A formalization of complex event stream processing
A formalization of complex event stream processingA formalization of complex event stream processing
A formalization of complex event stream processing
Sylvain Hallé
 
Use the Matplotlib, Luke @ PyCon Taiwan 2012
Use the Matplotlib, Luke @ PyCon Taiwan 2012Use the Matplotlib, Luke @ PyCon Taiwan 2012
Use the Matplotlib, Luke @ PyCon Taiwan 2012
Wen-Wei Liao
 
Ankita sharma focp
Ankita sharma focpAnkita sharma focp
Ankita sharma focp
AnkitaSharma463389
 
Data Applied:Outliers
Data Applied:OutliersData Applied:Outliers
Data Applied:Outliers
DataminingTools Inc
 
A lab report on modeling and simulation with python code
A lab report on modeling and simulation with python codeA lab report on modeling and simulation with python code
A lab report on modeling and simulation with python code
Alamgir Hossain
 
The matplotlib Library
The matplotlib LibraryThe matplotlib Library
The matplotlib Library
Haim Michael
 
USE OF PRINT IN PYTHON PART 2
USE OF PRINT IN PYTHON PART 2USE OF PRINT IN PYTHON PART 2
USE OF PRINT IN PYTHON PART 2
vikram mahendra
 
Theano vs TensorFlow | Edureka
Theano vs TensorFlow | EdurekaTheano vs TensorFlow | Edureka
Theano vs TensorFlow | Edureka
Edureka!
 
Lecture 1 mte 407
Lecture 1 mte 407Lecture 1 mte 407
Lecture 1 mte 407
rumanatasnim415
 
Lecture 1 mte 407
Lecture 1 mte 407Lecture 1 mte 407
Lecture 1 mte 407
rumanatasnim415
 
Wcbpijwbpij new
Wcbpijwbpij newWcbpijwbpij new
Wcbpijwbpij new
Hanokh Aloni
 
Expressions using operator in c
Expressions using operator in cExpressions using operator in c
Expressions using operator in c
Saranya saran
 
Csci101 lect01 first_program
Csci101 lect01 first_programCsci101 lect01 first_program
Csci101 lect01 first_program
Elsayed Hemayed
 

What's hot (19)

Dma
DmaDma
Dma
 
The TensorFlow dance craze
The TensorFlow dance crazeThe TensorFlow dance craze
The TensorFlow dance craze
 
String Manipulation Function and Header File Functions
String Manipulation Function and Header File FunctionsString Manipulation Function and Header File Functions
String Manipulation Function and Header File Functions
 
Function recap
Function recapFunction recap
Function recap
 
Matlab Nn Intro
Matlab Nn IntroMatlab Nn Intro
Matlab Nn Intro
 
A formalization of complex event stream processing
A formalization of complex event stream processingA formalization of complex event stream processing
A formalization of complex event stream processing
 
Use the Matplotlib, Luke @ PyCon Taiwan 2012
Use the Matplotlib, Luke @ PyCon Taiwan 2012Use the Matplotlib, Luke @ PyCon Taiwan 2012
Use the Matplotlib, Luke @ PyCon Taiwan 2012
 
Ankita sharma focp
Ankita sharma focpAnkita sharma focp
Ankita sharma focp
 
Data Applied:Outliers
Data Applied:OutliersData Applied:Outliers
Data Applied:Outliers
 
A lab report on modeling and simulation with python code
A lab report on modeling and simulation with python codeA lab report on modeling and simulation with python code
A lab report on modeling and simulation with python code
 
The matplotlib Library
The matplotlib LibraryThe matplotlib Library
The matplotlib Library
 
USE OF PRINT IN PYTHON PART 2
USE OF PRINT IN PYTHON PART 2USE OF PRINT IN PYTHON PART 2
USE OF PRINT IN PYTHON PART 2
 
Theano vs TensorFlow | Edureka
Theano vs TensorFlow | EdurekaTheano vs TensorFlow | Edureka
Theano vs TensorFlow | Edureka
 
Loop Statements [5] M
Loop Statements [5] MLoop Statements [5] M
Loop Statements [5] M
 
Lecture 1 mte 407
Lecture 1 mte 407Lecture 1 mte 407
Lecture 1 mte 407
 
Lecture 1 mte 407
Lecture 1 mte 407Lecture 1 mte 407
Lecture 1 mte 407
 
Wcbpijwbpij new
Wcbpijwbpij newWcbpijwbpij new
Wcbpijwbpij new
 
Expressions using operator in c
Expressions using operator in cExpressions using operator in c
Expressions using operator in c
 
Csci101 lect01 first_program
Csci101 lect01 first_programCsci101 lect01 first_program
Csci101 lect01 first_program
 

Similar to Dynamic allocation

dynamic_v1-3.pptx
dynamic_v1-3.pptxdynamic_v1-3.pptx
dynamic_v1-3.pptx
ngonidzashemutsipa
 
Pointers and Memory Allocation ESC101.pptx
Pointers and Memory Allocation ESC101.pptxPointers and Memory Allocation ESC101.pptx
Pointers and Memory Allocation ESC101.pptx
krishna50blogging
 
Lecture 18 - Pointers
Lecture 18 - PointersLecture 18 - Pointers
Lecture 18 - Pointers
Md. Imran Hossain Showrov
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Viji B
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
NewsMogul
 
dynamic-allocation.pdf
dynamic-allocation.pdfdynamic-allocation.pdf
dynamic-allocation.pdf
ngonidzashemutsipa
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory Allocation
Rabin BK
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Gem WeBlog
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptx
ssuser688516
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Naveen Gupta
 
DS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxDS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docx
VeerannaKotagi1
 
13. dynamic allocation
13. dynamic allocation13. dynamic allocation
13. dynamic allocation웅식 전
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
JawadTanvir
 
Input output functions
Input output functionsInput output functions
Input output functionshyderali123
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory management
Sreedhar Chowdam
 
Linked list
Linked listLinked list
Linked list
somuinfo123
 
Dynamic Memory allocation
Dynamic Memory allocationDynamic Memory allocation
Dynamic Memory allocation
Grishma Rajput
 
Dynamic Memory Allocation
Dynamic Memory AllocationDynamic Memory Allocation
Dynamic Memory Allocation
vaani pathak
 
DMA.pptx
DMA.pptxDMA.pptx
C programming day#2.
C programming day#2.C programming day#2.
C programming day#2.
Mohamed Fawzy
 

Similar to Dynamic allocation (20)

dynamic_v1-3.pptx
dynamic_v1-3.pptxdynamic_v1-3.pptx
dynamic_v1-3.pptx
 
Pointers and Memory Allocation ESC101.pptx
Pointers and Memory Allocation ESC101.pptxPointers and Memory Allocation ESC101.pptx
Pointers and Memory Allocation ESC101.pptx
 
Lecture 18 - Pointers
Lecture 18 - PointersLecture 18 - Pointers
Lecture 18 - Pointers
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
 
dynamic-allocation.pdf
dynamic-allocation.pdfdynamic-allocation.pdf
dynamic-allocation.pdf
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory Allocation
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptx
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
DS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxDS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docx
 
13. dynamic allocation
13. dynamic allocation13. dynamic allocation
13. dynamic allocation
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
 
Input output functions
Input output functionsInput output functions
Input output functions
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory management
 
Linked list
Linked listLinked list
Linked list
 
Dynamic Memory allocation
Dynamic Memory allocationDynamic Memory allocation
Dynamic Memory allocation
 
Dynamic Memory Allocation
Dynamic Memory AllocationDynamic Memory Allocation
Dynamic Memory Allocation
 
DMA.pptx
DMA.pptxDMA.pptx
DMA.pptx
 
C programming day#2.
C programming day#2.C programming day#2.
C programming day#2.
 

More from CGC Technical campus,Mohali

Gender Issues CS.pptx
Gender Issues CS.pptxGender Issues CS.pptx
Gender Issues CS.pptx
CGC Technical campus,Mohali
 
Intellectual Property Rights.pptx
Intellectual Property Rights.pptxIntellectual Property Rights.pptx
Intellectual Property Rights.pptx
CGC Technical campus,Mohali
 
Cyber Safety ppt.pptx
Cyber Safety ppt.pptxCyber Safety ppt.pptx
Cyber Safety ppt.pptx
CGC Technical campus,Mohali
 
Python Modules .pptx
Python Modules .pptxPython Modules .pptx
Python Modules .pptx
CGC Technical campus,Mohali
 
Arrays in c
Arrays in cArrays in c
Control statments in c
Control statments in cControl statments in c
Control statments in c
CGC Technical campus,Mohali
 
Operators in c by anupam
Operators in c by anupamOperators in c by anupam
Operators in c by anupam
CGC Technical campus,Mohali
 
Datatypes in c
Datatypes in cDatatypes in c
Fundamentals of-computer
Fundamentals of-computerFundamentals of-computer
Fundamentals of-computer
CGC Technical campus,Mohali
 
Searching
Searching Searching
File handling-c
File handling-cFile handling-c
Structure in C language
Structure in C languageStructure in C language
Structure in C language
CGC Technical campus,Mohali
 
Function in c program
Function in c programFunction in c program
Function in c program
CGC Technical campus,Mohali
 
Function in c
Function in cFunction in c
string in C
string in Cstring in C
C arrays
C arraysC arrays
Data processing and Report writing in Research(Section E)
Data processing and Report writing in Research(Section E)Data processing and Report writing in Research(Section E)
Data processing and Report writing in Research(Section E)
CGC Technical campus,Mohali
 
data analysis and report wring in research (Section d)
data analysis and report wring  in research (Section d)data analysis and report wring  in research (Section d)
data analysis and report wring in research (Section d)
CGC Technical campus,Mohali
 
Section C(Analytical and descriptive surveys... )
Section C(Analytical and descriptive surveys... )Section C(Analytical and descriptive surveys... )
Section C(Analytical and descriptive surveys... )
CGC Technical campus,Mohali
 

More from CGC Technical campus,Mohali (20)

Gender Issues CS.pptx
Gender Issues CS.pptxGender Issues CS.pptx
Gender Issues CS.pptx
 
Intellectual Property Rights.pptx
Intellectual Property Rights.pptxIntellectual Property Rights.pptx
Intellectual Property Rights.pptx
 
Cyber Safety ppt.pptx
Cyber Safety ppt.pptxCyber Safety ppt.pptx
Cyber Safety ppt.pptx
 
Python Modules .pptx
Python Modules .pptxPython Modules .pptx
Python Modules .pptx
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Control statments in c
Control statments in cControl statments in c
Control statments in c
 
Operators in c by anupam
Operators in c by anupamOperators in c by anupam
Operators in c by anupam
 
Datatypes in c
Datatypes in cDatatypes in c
Datatypes in c
 
Fundamentals of-computer
Fundamentals of-computerFundamentals of-computer
Fundamentals of-computer
 
Searching
Searching Searching
Searching
 
File handling-c
File handling-cFile handling-c
File handling-c
 
Structure in C language
Structure in C languageStructure in C language
Structure in C language
 
Intro
IntroIntro
Intro
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Function in c
Function in cFunction in c
Function in c
 
string in C
string in Cstring in C
string in C
 
C arrays
C arraysC arrays
C arrays
 
Data processing and Report writing in Research(Section E)
Data processing and Report writing in Research(Section E)Data processing and Report writing in Research(Section E)
Data processing and Report writing in Research(Section E)
 
data analysis and report wring in research (Section d)
data analysis and report wring  in research (Section d)data analysis and report wring  in research (Section d)
data analysis and report wring in research (Section d)
 
Section C(Analytical and descriptive surveys... )
Section C(Analytical and descriptive surveys... )Section C(Analytical and descriptive surveys... )
Section C(Analytical and descriptive surveys... )
 

Recently uploaded

S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
JEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questionsJEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questions
ShivajiThube2
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
Krisztián Száraz
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 

Recently uploaded (20)

S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
JEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questionsJEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questions
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 

Dynamic allocation

  • 1. Dynamic Memory Allocation Submitted to: Anupam Shrama Assistant Professor ,CSE Submitted by: (GROUP-14) SUNNY CHAKRABORTY-1915132 SUDHIR-1915131 SHIVANSHU-1915125 1
  • 2. 2 Problem with Arrays  Sometimes Amount of data cannot be predicted beforehand Number of data items keeps changing during program execution  Example: Seach for an element in an array of N elements  One solution: find the maximum possible value of N and allocate an array of N elements Wasteful of memory space, as N may be much smaller in some executions Example: maximum value of N may be 10,000, but a particular run may need to search only among 100 elements Using array of size 10,000 always wastes memory in most cases
  • 3. Better Solution Dynamic memory allocation Know how much memory is needed after the program is run Example: ask the user to enter from keyboard Dynamically allocate only the amount of memory needed C provides functions to dynamically allocate memory malloc, calloc, realloc 3
  • 4. 4 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.  We will only do malloc and free
  • 5. 5 Allocating a Block of Memory A block of memory can be allocated using the function malloc  Reserves a block of memory of specified size and returns a pointer of type void  The return pointer can be type-casted to any pointer type General format: type *p; p = (type *) malloc (byte_size);
  • 6. 6 Example p = (int *) malloc(100 * sizeof(int));  A memory space equivalent to 100 times the size of an int bytes is reserved  The address of the first byte of the allocated memory is assigned to the pointer p of type int p 400 bytes of space
  • 7. 7 Contd.  cptr = (char *) malloc (20); Allocates 20 bytes of space for the pointer cptr of type char  sptr = (struct stud *) malloc(10*sizeof(struct stud)); Allocates space for a structure array of 10 elements. sptr points to a structure element of type struct stud Always use sizeof operator to find number of bytes for a data type, as it can vary from machine to machine
  • 8. 8 Points to Note  malloc always allocates a block of contiguous bytes  The allocation can fail if sufficient contiguous memory space is not available  If it fails, malloc returns NULL if ((p = (int *) malloc(100 * sizeof(int))) == NULL) { printf (“n Memory cannot be allocated”); exit(); }
  • 9. Using the malloc’d Array  Once the memory is allocated, it can be used with pointers, or with array notation  Example: int *p, n, i; scanf(“%d”, &n); p = (int *) malloc (n * sizeof(int)); for (i=0; i<n; ++i) scanf(“%d”, &p[i]); The n integers allocated can be accessed as *p, *(p+1), *(p+2),…, *(p+n-1) or just as p[0], p[1], p[2], …,p[n-1] 9
  • 10. 10 Example printf("Input heights for %d students n",N); for (i=0; i<N; i++) scanf ("%f", &height[i]); for(i=0;i<N;i++) sum += height[i]; avg = sum / (float) N; printf("Average height = %f n", avg); free (height); return 0; } int main() { int i,N; float *height; float sum=0,avg; printf("Input no. of studentsn"); scanf("%d", &N); height = (float *) malloc(N * sizeof(float));
  • 11. malloc( )-ing array of structures 11 typedef struct{ char name[20]; int roll; float SGPA[8], CGPA; } person; void main() { person *student; int i,j,n; scanf("%d", &n); student = (person *)malloc(n*sizeof(person)); for (i=0; i<n; i++) { scanf("%s", student[i].name); scanf("%d", &student[i].roll); for(j=0;j<8;j++) scanf("%f", &student[i].SGPA[j]); scanf("%f", &student[i].CGPA); } }
  • 12. Dynamic Arrays of pointers 12 int main() { char word[20], **w; /* “**w” is a pointer to a pointer array */ int i, n; scanf("%d",&n); w = (char **) malloc (n * sizeof(char *)); for (i=0; i<n; ++i) { scanf("%s", word); w[i] = (char *) malloc ((strlen(word)+1)*sizeof(char)); strcpy (w[i], word) ; } for (i=0; i<n; i++) printf("w[%d] = %s n",i, w[i]); return 0; } 5 India Australia Kenya NewZealand SriLanka w[0] = India w[1] = Australia w[2] = Kenya w[3] = NewZealand w[4] = SriLanka Output
  • 13. How this will look like 13 w 0 1 2 3 4 I n d i a 0 S r i L a n k a 0 A u s t r a l I a 0 K e n y a 0 N e w Z e a l a n d 0
  • 14. free()14 The C library function void free(void *ptr) deallocates the memory previously allocated by a call to calloc, malloc, or realloc.
  • 15. 15