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

PPTX
#OOP_D_ITS - 3rd - Pointer And References
PPTX
Malloc() and calloc() in c
PPTX
#OOP_D_ITS - 2nd - C++ Getting Started
PPTX
Pointers
PPTX
Memory management CP
PDF
Programming the cloud with Skywriting
PPTX
Dynamic memory allocation
PDF
Matlab integration
#OOP_D_ITS - 3rd - Pointer And References
Malloc() and calloc() in c
#OOP_D_ITS - 2nd - C++ Getting Started
Pointers
Memory management CP
Programming the cloud with Skywriting
Dynamic memory allocation
Matlab integration

What's hot (19)

PPTX
PDF
The TensorFlow dance craze
PPTX
Function recap
PPT
Matlab Nn Intro
PDF
A formalization of complex event stream processing
PDF
Use the Matplotlib, Luke @ PyCon Taiwan 2012
DOCX
Ankita sharma focp
PPTX
Data Applied:Outliers
PDF
A lab report on modeling and simulation with python code
PDF
The matplotlib Library
PPTX
USE OF PRINT IN PYTHON PART 2
PDF
Theano vs TensorFlow | Edureka
PPT
Loop Statements [5] M
PPTX
Lecture 1 mte 407
PPTX
Lecture 1 mte 407
PPTX
Wcbpijwbpij new
PPTX
Expressions using operator in c
PPTX
Csci101 lect01 first_program
The TensorFlow dance craze
Function recap
Matlab Nn Intro
A formalization of complex event stream processing
Use the Matplotlib, Luke @ PyCon Taiwan 2012
Ankita sharma focp
Data Applied:Outliers
A lab report on modeling and simulation with python code
The matplotlib Library
USE OF PRINT IN PYTHON PART 2
Theano vs TensorFlow | Edureka
Loop Statements [5] M
Lecture 1 mte 407
Lecture 1 mte 407
Wcbpijwbpij new
Expressions using operator in c
Csci101 lect01 first_program
Ad

Similar to Dynamic allocation (20)

PPT
Bullet pts Dyn Mem Alloc.pptghftfhtfytftyft
PPTX
dynamic_v1-3.pptx
PPT
dynamic_v1-memory-management-in-c-cpp.ppt
PPTX
Dynamic Memory Allocation.pptx for c language and basic knowledge.
PPTX
Dynamic memory allocation
PPTX
Algoritmos e Estruturas de Dados - dynamic memory allocation
PPTX
PPTX
Structures_and_Files[1] - Read-Only.pptx
PDF
Data Structure - Dynamic Memory Allocation
PPTX
Dynamic Memory Allocation.pptx
PDF
dynamic-allocation.pdf
PDF
13. dynamic allocation
PPT
Dynamic memory allocation
PPTX
BBACA-SEM-III-Datastructure-PPT(0) for third semestetr
PPTX
Unit-9zxknaksldmoasdoiasmdmiojoisa(DMA).pptx
PPTX
Lecture 3.3.1 Dynamic Memory Allocation and Functions.pptx
DOCX
Dma
PDF
Memory Management for C and C++ _ language
PPT
DATA STRUCTURE AND APPLICATIONS -MODULE1.PPT
PDF
06 linked list
Bullet pts Dyn Mem Alloc.pptghftfhtfytftyft
dynamic_v1-3.pptx
dynamic_v1-memory-management-in-c-cpp.ppt
Dynamic Memory Allocation.pptx for c language and basic knowledge.
Dynamic memory allocation
Algoritmos e Estruturas de Dados - dynamic memory allocation
Structures_and_Files[1] - Read-Only.pptx
Data Structure - Dynamic Memory Allocation
Dynamic Memory Allocation.pptx
dynamic-allocation.pdf
13. dynamic allocation
Dynamic memory allocation
BBACA-SEM-III-Datastructure-PPT(0) for third semestetr
Unit-9zxknaksldmoasdoiasmdmiojoisa(DMA).pptx
Lecture 3.3.1 Dynamic Memory Allocation and Functions.pptx
Dma
Memory Management for C and C++ _ language
DATA STRUCTURE AND APPLICATIONS -MODULE1.PPT
06 linked list
Ad

More from CGC Technical campus,Mohali (20)

PPTX
Gender Issues CS.pptx
PPTX
Intellectual Property Rights.pptx
PPTX
Cyber Safety ppt.pptx
PPTX
Python Modules .pptx
PPT
Control statments in c
PPTX
Operators in c by anupam
PPTX
PPT
Fundamentals of-computer
PPT
PPTX
Structure in C language
PPTX
Function in c program
PPTX
PPTX
Data processing and Report writing in Research(Section E)
PPTX
data analysis and report wring in research (Section d)
PPTX
Section C(Analytical and descriptive surveys... )
Gender Issues CS.pptx
Intellectual Property Rights.pptx
Cyber Safety ppt.pptx
Python Modules .pptx
Control statments in c
Operators in c by anupam
Fundamentals of-computer
Structure in C language
Function in c program
Data processing and Report writing in Research(Section E)
data analysis and report wring in research (Section d)
Section C(Analytical and descriptive surveys... )

Recently uploaded (20)

PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Classroom Observation Tools for Teachers
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
01-Introduction-to-Information-Management.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Complications of Minimal Access Surgery at WLH
PPTX
master seminar digital applications in india
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Sports Quiz easy sports quiz sports quiz
PDF
RMMM.pdf make it easy to upload and study
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Microbial disease of the cardiovascular and lymphatic systems
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Classroom Observation Tools for Teachers
Insiders guide to clinical Medicine.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Microbial diseases, their pathogenesis and prophylaxis
O7-L3 Supply Chain Operations - ICLT Program
01-Introduction-to-Information-Management.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
102 student loan defaulters named and shamed – Is someone you know on the list?
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Complications of Minimal Access Surgery at WLH
master seminar digital applications in india
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
STATICS OF THE RIGID BODIES Hibbelers.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Sports Quiz easy sports quiz sports quiz
RMMM.pdf make it easy to upload and study
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Microbial disease of the cardiovascular and lymphatic systems

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