SlideShare ist ein Scribd-Unternehmen logo
1 von 15
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

Weitere ähnliche Inhalte

Was ist angesagt? (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
 

Ähnlich wie Dynamic allocation

Pointers and Memory Allocation ESC101.pptx
Pointers and Memory Allocation ESC101.pptxPointers and Memory Allocation ESC101.pptx
Pointers and Memory Allocation ESC101.pptxkrishna50blogging
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationViji B
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationRabin BK
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationGem WeBlog
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxssuser688516
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationNaveen Gupta
 
DS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxDS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxVeerannaKotagi1
 
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.pptxJawadTanvir
 
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 managementSreedhar Chowdam
 
Dynamic Memory allocation
Dynamic Memory allocationDynamic Memory allocation
Dynamic Memory allocationGrishma Rajput
 
Dynamic Memory Allocation
Dynamic Memory AllocationDynamic Memory Allocation
Dynamic Memory Allocationvaani pathak
 
C programming day#2.
C programming day#2.C programming day#2.
C programming day#2.Mohamed Fawzy
 

Ähnlich wie 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.
 

Mehr von CGC Technical campus,Mohali

Mehr von 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... )
 

Kürzlich hochgeladen

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
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
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
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 

Kürzlich hochgeladen (20)

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
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
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
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 

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