SlideShare a Scribd company logo
1 of 22
1
Dynamic Memory Allo
cation
Group 4
Software Engineering
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 p
articular run may need to search only among 100 elem
ents
 Using array of size 10,000 always wastes memory i
n 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 nee
ded
 C provides functions to dynamically allocate me
mory
 malloc, calloc, realloc
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 mem
ory.
 free
 Frees previously allocated space.
 realloc
 Modifies the size of previously allocated space.
 We will only do malloc and free
C Library - <stdlib.h>
5
6
7
Allocating a Block of Memory
 A block of memory can be allocated using the fu
nction malloc
Reserves a block of memory of specified size
and returns a pointer of type void
It returns a pointer that can be type-casted to
any pointer type. It points to the first byte of th
e allocated memory, else returns NULL.
 General format:
type *p;
p = (type *) malloc (byte_size);
8
Example
p = (int *) malloc(100 * sizeof(int));
 A memory space equivalent to 100 times t
he size of an int bytes is reserved
The address of the first byte of the allocate
d memory is assigned to the pointer p of ty
pe int
p
400 bytes of space
9
Contd.
 cptr = (char *) malloc (20);
Allocates 20 bytes of space for the pointer cptr
of type char
 sptr = (struct stud *) malloc(10*sizeof(struct stu
d));
Allocates space for a structure array of 10 elem
ents. 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
10
Points to Note
 malloc always allocates a block of contiguou
s bytes
The allocation can fail if sufficient contiguo
us 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();
}
11
Using the malloc’d Array
 Once the memory is allocated, it can be used with pointer
s, 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]
12
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Amount of allocated memory: %i bytesnnn", n1 * sizeof(int));
printf("Addresses of previously allocated memory:n");
for(i = 0; i < n1; ++i)
printf("%pcn",ptr + i);
printf("nEnter the new size: ");
scanf("%d", &n2);
// rellocating the memory
ptr = realloc(ptr, n2 * sizeof(int));
printf("Addresses of newly allocated memory:n");
for(i = 0; i < n2; ++i)
printf("%pcn", ptr + i);
free(ptr);
return 0;
}
13
Releasing the Allocated Space: fre
e()
 An allocated block can be returned to the syste
m for future use by using the free function
 To deallocate the memory we use the General s
yntax:
free (ptr);
where ptr is a pointer to a memory block which
has been previously created using malloc
 Note that no size needs to be mentioned for the
allocated block, the system remembers it for ea
ch pointer returned
14
15
16
malloc( )-ing array of structures
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);
}
}
calloc()
Description
The C library function void *calloc(size_t nitems, size_t size) allocates the requ
ested memory and returns a pointer to it. The difference in malloc and calloc is
that malloc does not set the memory to zero where as calloc sets allocated me
mory to zero.
Declaration
Following is the declaration for calloc() function.
void *calloc(size_t nitems, size_t size)
17
// Program to calculate the sum of n numbers entered by the user
// The calloc() function allocates memory and initializes all bits to zero.
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) calloc(n, sizeof(int));
printf("Amount of allocated memory: %i bytesnnn", n * sizeof(int));
if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
realloc()
Description
The C library function void *realloc(void *ptr, size_t size) attempts to resize the
memory block pointed to by ptr that was previously allocated with a call to mallo
c or calloc.
Declaration
Following is the declaration for realloc() function.
void *realloc(void *ptr, size_t size)
Parameters
ptr − This is the pointer to a memory block previously allocated with malloc, call
oc or realloc to be reallocated. If this is NULL, a new block is allocated and a po
inter to it is returned by the function.
size − This is the new size for the memory block, in bytes. If it is 0 and ptr point
s to an existing block of memory, the memory block pointed by ptr is deallocate
d and a NULL pointer is returned.
19
Return Value
This function returns a pointer to the newly allocated memory, or NULL
if the request fails.
20
21
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Amount of allocated memory: %i bytesnnn", n1 * sizeof(int));
printf("Addresses of previously allocated memory:n");
for(i = 0; i < n1; ++i)
printf("%pcn",ptr + i);
printf("nEnter the new size: ");
scanf("%d", &n2);
// rellocating the memory
ptr = realloc(ptr, n2 * sizeof(int));
printf("Addresses of newly allocated memory:n");
for(i = 0; i < n2; ++i)
printf("%pcn", ptr + i);
free(ptr);
return 0;
}
22

More Related Content

Similar to dynamic_v1-3.pptx

Similar to dynamic_v1-3.pptx (20)

DS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxDS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docx
 
Dynamic Memory Allocation in C
Dynamic Memory Allocation in CDynamic Memory Allocation in C
Dynamic Memory Allocation in C
 
Pointers and Memory Allocation ESC101.pptx
Pointers and Memory Allocation ESC101.pptxPointers and Memory Allocation ESC101.pptx
Pointers and Memory Allocation ESC101.pptx
 
Data Structure - Dynamic Memory Allocation
Data Structure - Dynamic Memory AllocationData Structure - Dynamic Memory Allocation
Data Structure - Dynamic Memory Allocation
 
Linked list
Linked listLinked list
Linked list
 
Memory Management.pptx
Memory Management.pptxMemory Management.pptx
Memory Management.pptx
 
Lecture 18 - Pointers
Lecture 18 - PointersLecture 18 - Pointers
Lecture 18 - Pointers
 
13. dynamic allocation
13. dynamic allocation13. dynamic allocation
13. dynamic allocation
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
dynamic-allocation.pdf
dynamic-allocation.pdfdynamic-allocation.pdf
dynamic-allocation.pdf
 
1. C Basics for Data Structures Bridge Course
1. C Basics for Data Structures   Bridge Course1. C Basics for Data Structures   Bridge Course
1. C Basics for Data Structures Bridge Course
 
Dynamic Memory Allocation
Dynamic Memory AllocationDynamic Memory Allocation
Dynamic Memory Allocation
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory management
 
Dma
DmaDma
Dma
 
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
 
Dma
DmaDma
Dma
 
Stack & heap
Stack & heap Stack & heap
Stack & heap
 
DMA.pptx
DMA.pptxDMA.pptx
DMA.pptx
 

Recently uploaded

Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 

Recently uploaded (20)

Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 

dynamic_v1-3.pptx

  • 1. 1 Dynamic Memory Allo cation Group 4 Software Engineering
  • 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 p articular run may need to search only among 100 elem ents  Using array of size 10,000 always wastes memory i n most cases
  • 3. 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 nee ded  C provides functions to dynamically allocate me mory  malloc, calloc, realloc
  • 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 mem ory.  free  Frees previously allocated space.  realloc  Modifies the size of previously allocated space.  We will only do malloc and free
  • 5. C Library - <stdlib.h> 5
  • 6. 6
  • 7. 7 Allocating a Block of Memory  A block of memory can be allocated using the fu nction malloc Reserves a block of memory of specified size and returns a pointer of type void It returns a pointer that can be type-casted to any pointer type. It points to the first byte of th e allocated memory, else returns NULL.  General format: type *p; p = (type *) malloc (byte_size);
  • 8. 8 Example p = (int *) malloc(100 * sizeof(int));  A memory space equivalent to 100 times t he size of an int bytes is reserved The address of the first byte of the allocate d memory is assigned to the pointer p of ty pe int p 400 bytes of space
  • 9. 9 Contd.  cptr = (char *) malloc (20); Allocates 20 bytes of space for the pointer cptr of type char  sptr = (struct stud *) malloc(10*sizeof(struct stu d)); Allocates space for a structure array of 10 elem ents. 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
  • 10. 10 Points to Note  malloc always allocates a block of contiguou s bytes The allocation can fail if sufficient contiguo us 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(); }
  • 11. 11 Using the malloc’d Array  Once the memory is allocated, it can be used with pointer s, 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]
  • 12. 12 #include <stdio.h> #include <stdlib.h> int main() { int *ptr, i , n1, n2; printf("Enter size: "); scanf("%d", &n1); ptr = (int*) malloc(n1 * sizeof(int)); printf("Amount of allocated memory: %i bytesnnn", n1 * sizeof(int)); printf("Addresses of previously allocated memory:n"); for(i = 0; i < n1; ++i) printf("%pcn",ptr + i); printf("nEnter the new size: "); scanf("%d", &n2); // rellocating the memory ptr = realloc(ptr, n2 * sizeof(int)); printf("Addresses of newly allocated memory:n"); for(i = 0; i < n2; ++i) printf("%pcn", ptr + i); free(ptr); return 0; }
  • 13. 13 Releasing the Allocated Space: fre e()  An allocated block can be returned to the syste m for future use by using the free function  To deallocate the memory we use the General s yntax: free (ptr); where ptr is a pointer to a memory block which has been previously created using malloc  Note that no size needs to be mentioned for the allocated block, the system remembers it for ea ch pointer returned
  • 14. 14
  • 15. 15
  • 16. 16 malloc( )-ing array of structures 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); } }
  • 17. calloc() Description The C library function void *calloc(size_t nitems, size_t size) allocates the requ ested memory and returns a pointer to it. The difference in malloc and calloc is that malloc does not set the memory to zero where as calloc sets allocated me mory to zero. Declaration Following is the declaration for calloc() function. void *calloc(size_t nitems, size_t size) 17
  • 18. // Program to calculate the sum of n numbers entered by the user // The calloc() function allocates memory and initializes all bits to zero. #include <stdio.h> #include <stdlib.h> int main() { int n, i, *ptr, sum = 0; printf("Enter number of elements: "); scanf("%d", &n); ptr = (int*) calloc(n, sizeof(int)); printf("Amount of allocated memory: %i bytesnnn", n * sizeof(int)); if(ptr == NULL) { printf("Error! memory not allocated."); exit(0); } printf("Enter elements: "); for(i = 0; i < n; ++i) { scanf("%d", ptr + i); sum += *(ptr + i); } printf("Sum = %d", sum); free(ptr); return 0; }
  • 19. realloc() Description The C library function void *realloc(void *ptr, size_t size) attempts to resize the memory block pointed to by ptr that was previously allocated with a call to mallo c or calloc. Declaration Following is the declaration for realloc() function. void *realloc(void *ptr, size_t size) Parameters ptr − This is the pointer to a memory block previously allocated with malloc, call oc or realloc to be reallocated. If this is NULL, a new block is allocated and a po inter to it is returned by the function. size − This is the new size for the memory block, in bytes. If it is 0 and ptr point s to an existing block of memory, the memory block pointed by ptr is deallocate d and a NULL pointer is returned. 19
  • 20. Return Value This function returns a pointer to the newly allocated memory, or NULL if the request fails. 20
  • 21. 21 #include <stdio.h> #include <stdlib.h> int main() { int *ptr, i , n1, n2; printf("Enter size: "); scanf("%d", &n1); ptr = (int*) malloc(n1 * sizeof(int)); printf("Amount of allocated memory: %i bytesnnn", n1 * sizeof(int)); printf("Addresses of previously allocated memory:n"); for(i = 0; i < n1; ++i) printf("%pcn",ptr + i); printf("nEnter the new size: "); scanf("%d", &n2); // rellocating the memory ptr = realloc(ptr, n2 * sizeof(int)); printf("Addresses of newly allocated memory:n"); for(i = 0; i < n2; ++i) printf("%pcn", ptr + i); free(ptr); return 0; }
  • 22. 22