SlideShare uma empresa Scribd logo
1 de 13
Dynamic memory allocation
Dynamic memory allocation
• The process of allocating memory at run
time is known as dynamic memory
allocation.
• Although c does not inherently have this
facility there are four library routines which
allow this function.
• The following functions are used in c for
purpose of memory management.
Dynamic memory allocation
•
•
•

•
•
•
•

malloc()
Allocates memory requests size of bytes and returns
a pointer to the Ist byte of allocated space
calloc()
Allocates space for an array of elements initializes
them to zero and returns a pointer to the memory
free()
Frees previously allocated space
realloc()
Modifies the size of previously allocated space.
Dynamic memory allocation
• Memory allocations process
• The free memory region is called the heap.
• The size of heap keeps changing when program
is executed due to creation and death of
variables.
• Therefore it is possible to encounter memory
overflow during dynamic allocation process.
• In such situations, the memory allocation
functions mentioned above will return a null
pointer.
Dynamic memory allocation
• Allocating a block of memory:
• A block of memory may be allocated using
the function malloc().
• The malloc function reserves a block of
memory of specified size and returns a
pointer of type void.
• This means that we can assign it to any type
of pointer. It takes the following form:

ptr=(cast-type*)malloc(byte-size);
Dynamic memory allocation
• ptr is a pointer of type cast-type the malloc()
returns a pointer (of cast type) to an area of
memory with size byte-size.
• Example:

x=(int*)malloc(100*sizeof(int));
• a memory equivalent to 100 times the area
of int bytes is reserved and the address of
the first byte of memory allocated is
assigned to the pointer x of type int
Dynamic memory allocation

• Allocating multiple blocks of memory
• Calloc is another memory allocation function that is
normally used to request multiple blocks of storage
each of the same size and then sets all bytes to zero.
• The general form of calloc is:

ptr=(cast-type*) calloc(n,elem-size);
• The above statement allocates contiguous space for
n blocks each size of elements size bytes.
• All bytes are initialized to zero and a pointer to the
first byte of the allocated region is returned. If there
is not enough space a null pointer is returned.
Dynamic memory allocation
• Releasing the used space:
• Compile time storage of a variable is
allocated and released by the system in
accordance with its storage class.
• With the dynamic runtime allocation, it is
our responsibility to release the space when
it is not required.
•
Dynamic memory allocation
• Releasing the used space:
• The release of storage space becomes important when the
storage is limited. When we no longer need the data we
stored in a block of memory and we do not intend to use
that block for storing any other information, we may
release that block of memory for future use, using the free
function.

free(ptr);

• ptr is a pointer that has been created by using malloc or
calloc.
Dynamic memory allocation

• To alter the size of allocated memory:
• The memory allocated by using calloc or malloc might be
insufficient or excess sometimes in both the situations
we can change the memory size already allocated with
the help of the function realloc().
• This process is called reallocation of memory.
• The general statement of reallocation of memory is :

ptr=realloc(ptr,newsize);
• This function allocates new memory space of size
newsize to the pointer variable ptr ans returns a pointer
to the first byte of the memory block.
• The allocated new block may be or may not be at the
same region.
•
•
•
•
•
•
•
•
•
•
•
•
•

Dynamic memory allocation
malloc() example
#include <stdio.h>
#include <conio.h>
#include <alloc.h>
void main()
{
int *ptr;
ptr=(int *)malloc(2);
scanf("%d",ptr);
printf("value= %d",*ptr);
free(ptr); /* free allocated memory */
getch();
}
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•

Dynamic memory allocation
Calloc() example
#include <stdio.h>
#include <conio.h>
#include <alloc.h>
void main()
{
int *ptr,i,n;
printf("enter limit ");
scanf("%d",&n);
ptr=(int *)calloc(n,2);
for(i=1;i<=n;i++)
{
printf("Enter %d no :- ",i);
scanf("%d",ptr);
ptr++;
}

•
•
•
•
•
•
•
•

ptr=ptr-n;
printf("n given nos ");
for(i=1;i<=n;i++)
{
printf("%d ",*ptr);
ptr++;
}
free(ptr); /* free allocated
memory */
•
getch();
• }
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•

Dynamic memory allocation
Realloc() example
#include <stdio.h>
#include <conio.h>
#include <alloc.h>
void main()
{
int *ptr,i,n;
printf("enter limit ");
scanf("%d",&n);
ptr=(int *)calloc(n,2);
for(i=1;i<=n;i++)
{
printf("Enter %d no :- ",i);
scanf("%d",ptr);
ptr++;
}

•
•
•
•
•
•
•
•
•

ptr=ptr-n;
printf("n given nos ");
for(i=1;i<=n;i++)
{
printf("%d ",*ptr);
ptr++;
}
ptr=(int *)realloc(ptr,3);
free(ptr); /* free allocated
memory */
•
getch();
• }

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Dynamic memory allocation in c language
Dynamic memory allocation in c languageDynamic memory allocation in c language
Dynamic memory allocation in c language
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in c
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Malloc() and calloc() in c
Malloc() and calloc() in cMalloc() and calloc() in c
Malloc() and calloc() in c
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Dynamic Memory Allocation
Dynamic Memory AllocationDynamic Memory Allocation
Dynamic Memory Allocation
 
Dynamic Memory allocation
Dynamic Memory allocationDynamic Memory allocation
Dynamic Memory allocation
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Stack & heap
Stack & heap Stack & heap
Stack & heap
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory Allocation
 
Stack and heap allocation
Stack and heap allocationStack and heap allocation
Stack and heap allocation
 
Stack and heap
Stack and heapStack and heap
Stack and heap
 
Memory allocation (4)
Memory allocation (4)Memory allocation (4)
Memory allocation (4)
 
Dma
DmaDma
Dma
 
Dma
DmaDma
Dma
 
Functions with heap and stack
Functions with heap and stackFunctions with heap and stack
Functions with heap and stack
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
Intoduction to dynamic memory allocation
Intoduction to dynamic memory allocationIntoduction to dynamic memory allocation
Intoduction to dynamic memory allocation
 
Memory allocation
Memory allocationMemory allocation
Memory allocation
 
13. dynamic allocation
13. dynamic allocation13. dynamic allocation
13. dynamic allocation
 

Semelhante a 4 dynamic memory allocation

Data Structure - Dynamic Memory Allocation
Data Structure - Dynamic Memory AllocationData Structure - Dynamic Memory Allocation
Data Structure - Dynamic Memory Allocationbabuk110
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationGaurav Mandal
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationUTTAM VERMA
 
dynamicmemoryallocation.pptx
dynamicmemoryallocation.pptxdynamicmemoryallocation.pptx
dynamicmemoryallocation.pptxNiharika606186
 
Memory Management.pptx
Memory Management.pptxMemory Management.pptx
Memory Management.pptxBilalImran17
 
PF UE LEC 7 Pointers programming fundamentals (2).pptx
PF UE LEC 7 Pointers programming fundamentals (2).pptxPF UE LEC 7 Pointers programming fundamentals (2).pptx
PF UE LEC 7 Pointers programming fundamentals (2).pptxhelpme43
 
DYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxDYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxLECO9
 
DYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxDYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxSKUP1
 
Memory Allocation & Direct Memory Allocation in C & C++ Language PPT
Memory Allocation & Direct Memory Allocation in C & C++ Language PPTMemory Allocation & Direct Memory Allocation in C & C++ Language PPT
Memory Allocation & Direct Memory Allocation in C & C++ Language PPTAkhilMishra50
 
GLA University is inviting you to a scheduled Zoom meeting
GLA University is inviting you to a scheduled Zoom meetingGLA University is inviting you to a scheduled Zoom meeting
GLA University is inviting you to a scheduled Zoom meetingArun Kumar
 
Dynamic Memory Allocation In C
Dynamic Memory Allocation In CDynamic Memory Allocation In C
Dynamic Memory Allocation In CSimplilearn
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationViji B
 
Linux kernel memory allocators
Linux kernel memory allocatorsLinux kernel memory allocators
Linux kernel memory allocatorsHao-Ran Liu
 
Memory management CP
Memory management  CPMemory management  CP
Memory management CPShubham Sinha
 

Semelhante a 4 dynamic memory allocation (20)

Data Structure - Dynamic Memory Allocation
Data Structure - Dynamic Memory AllocationData Structure - Dynamic Memory Allocation
Data Structure - Dynamic Memory Allocation
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
dynamicmemoryallocation.pptx
dynamicmemoryallocation.pptxdynamicmemoryallocation.pptx
dynamicmemoryallocation.pptx
 
Memory Management.pptx
Memory Management.pptxMemory Management.pptx
Memory Management.pptx
 
final GROUP 4.pptx
final GROUP 4.pptxfinal GROUP 4.pptx
final GROUP 4.pptx
 
PF UE LEC 7 Pointers programming fundamentals (2).pptx
PF UE LEC 7 Pointers programming fundamentals (2).pptxPF UE LEC 7 Pointers programming fundamentals (2).pptx
PF UE LEC 7 Pointers programming fundamentals (2).pptx
 
DYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxDYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptx
 
DYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxDYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptx
 
C- language Lecture 6
C- language Lecture 6C- language Lecture 6
C- language Lecture 6
 
Memory Allocation & Direct Memory Allocation in C & C++ Language PPT
Memory Allocation & Direct Memory Allocation in C & C++ Language PPTMemory Allocation & Direct Memory Allocation in C & C++ Language PPT
Memory Allocation & Direct Memory Allocation in C & C++ Language PPT
 
GLA University is inviting you to a scheduled Zoom meeting
GLA University is inviting you to a scheduled Zoom meetingGLA University is inviting you to a scheduled Zoom meeting
GLA University is inviting you to a scheduled Zoom meeting
 
Dynamic Memory Allocation In C
Dynamic Memory Allocation In CDynamic Memory Allocation In C
Dynamic Memory Allocation In C
 
Dynamic Memory Allocation in C
Dynamic Memory Allocation in CDynamic Memory Allocation in C
Dynamic Memory Allocation in C
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Introduction to c part -3
Introduction to c   part -3Introduction to c   part -3
Introduction to c part -3
 
Linux kernel memory allocators
Linux kernel memory allocatorsLinux kernel memory allocators
Linux kernel memory allocators
 
dynamic_v1-3.pptx
dynamic_v1-3.pptxdynamic_v1-3.pptx
dynamic_v1-3.pptx
 
Functions with heap and stack
Functions with heap and stackFunctions with heap and stack
Functions with heap and stack
 
Memory management CP
Memory management  CPMemory management  CP
Memory management CP
 

Mais de Frijo Francis (12)

Type conversion
Type conversionType conversion
Type conversion
 
Structure
StructureStructure
Structure
 
Recursion prog
Recursion progRecursion prog
Recursion prog
 
Recursion prog (1)
Recursion prog (1)Recursion prog (1)
Recursion prog (1)
 
Pointers
PointersPointers
Pointers
 
Data type
Data typeData type
Data type
 
C programming language
C programming languageC programming language
C programming language
 
Break and continue
Break and continueBreak and continue
Break and continue
 
6 enumerated, typedef
6 enumerated, typedef6 enumerated, typedef
6 enumerated, typedef
 
5bit field
5bit field5bit field
5bit field
 
Union
UnionUnion
Union
 
1file handling
1file handling1file handling
1file handling
 

Último

ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 

Último (20)

ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 

4 dynamic memory allocation

  • 2. Dynamic memory allocation • The process of allocating memory at run time is known as dynamic memory allocation. • Although c does not inherently have this facility there are four library routines which allow this function. • The following functions are used in c for purpose of memory management.
  • 3. Dynamic memory allocation • • • • • • • malloc() Allocates memory requests size of bytes and returns a pointer to the Ist byte of allocated space calloc() Allocates space for an array of elements initializes them to zero and returns a pointer to the memory free() Frees previously allocated space realloc() Modifies the size of previously allocated space.
  • 4. Dynamic memory allocation • Memory allocations process • The free memory region is called the heap. • The size of heap keeps changing when program is executed due to creation and death of variables. • Therefore it is possible to encounter memory overflow during dynamic allocation process. • In such situations, the memory allocation functions mentioned above will return a null pointer.
  • 5. Dynamic memory allocation • Allocating a block of memory: • A block of memory may be allocated using the function malloc(). • The malloc function reserves a block of memory of specified size and returns a pointer of type void. • This means that we can assign it to any type of pointer. It takes the following form: ptr=(cast-type*)malloc(byte-size);
  • 6. Dynamic memory allocation • ptr is a pointer of type cast-type the malloc() returns a pointer (of cast type) to an area of memory with size byte-size. • Example: x=(int*)malloc(100*sizeof(int)); • a memory equivalent to 100 times the area of int bytes is reserved and the address of the first byte of memory allocated is assigned to the pointer x of type int
  • 7. Dynamic memory allocation • Allocating multiple blocks of memory • Calloc is another memory allocation function that is normally used to request multiple blocks of storage each of the same size and then sets all bytes to zero. • The general form of calloc is: ptr=(cast-type*) calloc(n,elem-size); • The above statement allocates contiguous space for n blocks each size of elements size bytes. • All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not enough space a null pointer is returned.
  • 8. Dynamic memory allocation • Releasing the used space: • Compile time storage of a variable is allocated and released by the system in accordance with its storage class. • With the dynamic runtime allocation, it is our responsibility to release the space when it is not required. •
  • 9. Dynamic memory allocation • Releasing the used space: • The release of storage space becomes important when the storage is limited. When we no longer need the data we stored in a block of memory and we do not intend to use that block for storing any other information, we may release that block of memory for future use, using the free function. free(ptr); • ptr is a pointer that has been created by using malloc or calloc.
  • 10. Dynamic memory allocation • To alter the size of allocated memory: • The memory allocated by using calloc or malloc might be insufficient or excess sometimes in both the situations we can change the memory size already allocated with the help of the function realloc(). • This process is called reallocation of memory. • The general statement of reallocation of memory is : ptr=realloc(ptr,newsize); • This function allocates new memory space of size newsize to the pointer variable ptr ans returns a pointer to the first byte of the memory block. • The allocated new block may be or may not be at the same region.
  • 11. • • • • • • • • • • • • • Dynamic memory allocation malloc() example #include <stdio.h> #include <conio.h> #include <alloc.h> void main() { int *ptr; ptr=(int *)malloc(2); scanf("%d",ptr); printf("value= %d",*ptr); free(ptr); /* free allocated memory */ getch(); }
  • 12. • • • • • • • • • • • • • • • • Dynamic memory allocation Calloc() example #include <stdio.h> #include <conio.h> #include <alloc.h> void main() { int *ptr,i,n; printf("enter limit "); scanf("%d",&n); ptr=(int *)calloc(n,2); for(i=1;i<=n;i++) { printf("Enter %d no :- ",i); scanf("%d",ptr); ptr++; } • • • • • • • • ptr=ptr-n; printf("n given nos "); for(i=1;i<=n;i++) { printf("%d ",*ptr); ptr++; } free(ptr); /* free allocated memory */ • getch(); • }
  • 13. • • • • • • • • • • • • • • • • Dynamic memory allocation Realloc() example #include <stdio.h> #include <conio.h> #include <alloc.h> void main() { int *ptr,i,n; printf("enter limit "); scanf("%d",&n); ptr=(int *)calloc(n,2); for(i=1;i<=n;i++) { printf("Enter %d no :- ",i); scanf("%d",ptr); ptr++; } • • • • • • • • • ptr=ptr-n; printf("n given nos "); for(i=1;i<=n;i++) { printf("%d ",*ptr); ptr++; } ptr=(int *)realloc(ptr,3); free(ptr); /* free allocated memory */ • getch(); • }