SlideShare a Scribd company logo
Programming Fundamentals
Lecture 9
Dynamic memory allocation in C and in C++,
dangling pointer, memory leak
Dynamic memory allocation
• Dynamic memory allocation in C/C++ refers to performing memory
allocation manually by programmer.
• The most important use is flexibility provided to programmers. We
are free to allocate and deallocate memory whenever we need and
whenever we don’t need anymore.
Dynamic memory allocation
• For normal variables like “int a”, “char str[10]”, etc, memory is
automatically allocated and deallocated. For dynamically allocated
memory it is programmers responsibility to deallocate memory when
no longer needed.
malloc- C function supported in C++
• “malloc” or “memory allocation” method in C is used to dynamically
allocate a single large block of memory with the specified size. It returns a
pointer of type void which can be cast into a pointer of any form.
• ptr = (cast-type*) malloc(byte-size)
• ptr = (int*) malloc(100 * sizeof(int));
• Since the size of int is 4 bytes, this statement will allocate 400 bytes of
memory. And, the pointer ptr holds the address of the first byte in the
allocated memory.
• Header file: cstdlib
int main()
{
// This pointer will hold the base address of the block
created
int* ptr;
int n, i, sum = 0;
// Get the number of elements for the array
cin>>n;
// Dynamically allocate memory using malloc()
ptr = (int*)malloc(n * sizeof(int));
// Check if the memory has been successfully allocated
by malloc or not
if (ptr == NULL) {
cout<<"Memory not allocated.n";
exit();
}
else {
// Memory has been successfully allocated
cout<<"Memory successfully allocated using malloc.n“;
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
cout<<"The elements of the array are: ";
for (i = 0; i < n; ++i) {
cout<<ptr[i];
}
}
return 0;
}
Calloc
• “calloc” or “contiguous allocation” method in C is used to
dynamically allocate the specified number of blocks of memory of the
specified type. It initializes each block with a default value ‘0’.
• ptr = (cast-type*)calloc(n, element-size);
• ptr = (float*) calloc(25, sizeof(float));
• This statement allocates contiguous space in memory for 25 elements
each with the size of the float
free
• “free” method in C is used to dynamically de-allocate the memory.
The memory allocated using functions malloc() and calloc() is not de-
allocated on their own. Hence the free() method is used, whenever
the dynamic memory allocation takes place. It helps to reduce
wastage of memory by freeing it.
• free(ptr);
realloc
• “realloc” or “re-allocation” method in C is used to dynamically
change the memory allocation of a previously allocated memory. In
other words, if the memory previously allocated with the help of
malloc or calloc is insufficient, realloc can be used to dynamically re-
allocate memory.
• ptr = realloc(ptr, newSize); where ptr is
reallocated with new size 'newSize'.
// use: taking array size again from user in a program
new operator
• The new operator denotes a request for memory allocation. If
sufficient memory is available, new operator initializes the memory
and returns the address of the newly allocated and initialized memory
to the pointer variable.
pointer-variable = new data-type;
int *p = NULL; p = new int;
int *p = new int;
Initialize the memory
• pointer-variable = new data-type(value);
• Example: int *p = new int(25); float *q = new
float(75.25);
Allocate block of memory
• new operator is also used to allocate a block(an array) of memory of
type data-type.
• pointer-variable = new data-type[size];
• Example: int *p = new int[10]
Dynamically allocates memory for 10 integers continuously of type int
and returns pointer to the first element of the sequence, which is
assigned to p(a pointer). p[0] refers to first element, p[1] refers to
second element and so on.
delete operator
• // Release memory pointed by pointer-variable delete
pointer-variable;
• Here, pointer-variable is the pointer that points to the data object created
by new.
delete p;
To free the dynamically allocated array pointed by pointer-variable, use
following form of delete:
// Release block of memory pointed by pointer-variable
delete[] pointer-variable;
Example: // It will free the entire array pointed by p.
delete[] p;
// C++ program to illustrate dynamic allocation
// and deallocation of memory using new and delete
#include <iostream>
using namespace std;
int main ()
{
// Pointer initialization to null
int* p = NULL;
// Request memory for the variable using new
operator
p = new int;
if (p==NULL)
cout << "allocation of memory failedn";
else
{
// Store value at allocated address
*p = 29;
cout << "Value of p: " << *p << endl;
}
// Request block of memory using new operator
float *r = new float(75.25);
cout << "Value of r: " << *r << endl;
// Request block of memory of size n
int n = 5;
int *q = new int[n];
if (q==NULL)
cout << "allocation of memory failedn";
else
{ for (int i = 0; i < n; i++)
q[i] = i+1;
cout << "Value store in block of memory: ";
for (int i = 0; i < n; i++)
cout << q[i] << " ";
}
// freed the allocated memory
delete p;
delete r;
// freed the block of allocated memory
delete[] q;
return 0; }
Dangling pointer
• A situation when a pointer points to the memory location of the
deallocated memory. It is important to make a pointer NULL after de-
allocating its allocated memory.
• Example of that situation could be when two pointers pointing to
same memory location and one deallocates that memory.
Memory leak
• A memory leak occurs in C++ when you allocate memory dynamically
and never give it back.
• The memory leak occurs, when a piece of memory which was
previously allocated by the programmer. Then it is not deallocated
properly by programmer. That memory is no longer in use by the
program. So that place is reserved for no reason. That’s why this is
called the memory leak.
• For the memory leak, some block of memory may have wasted. If the
system has enough memory, in that case also this may slow down the
performance.
References
• C++ How to Program
By Deitel & Deitel
• The C++ Programming Language
By Bjarne Stroustrup
• Object oriented programming using C++ by Tasleem Mustafa, Imran Saeed, Tariq Mehmood, Ahsan Raza
• https://www.tutorialspoint.com/cplusplus
• http://ecomputernotes.com/cpp/introduction-to-oop
• http://www.cplusplus.com/doc/tutorial
• http://www.c4learn.com/c-programming/c-dangling-pointer-causes/
• https://www.guru99.com/c-loop-statement.html
• www.w3schools.com
• https://www.geeksforgeeks.org/

More Related Content

Similar to PF UE LEC 7 Pointers programming fundamentals (2).pptx

Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++Tech_MX
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptx
ssuser688516
 
(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings
Nico Ludwig
 
Dynamic Memory allocation
Dynamic Memory allocationDynamic Memory allocation
Dynamic Memory allocation
Grishma Rajput
 
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
Arun Kumar
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in c
lavanya marichamy
 
1. C Basics for Data Structures Bridge Course
1. C Basics for Data Structures   Bridge Course1. C Basics for Data Structures   Bridge Course
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Mohammad Usman
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Gem WeBlog
 
dynamic-allocation.pdf
dynamic-allocation.pdfdynamic-allocation.pdf
dynamic-allocation.pdf
ngonidzashemutsipa
 
Dynamic Memory Allocation in C
Dynamic Memory Allocation in CDynamic Memory Allocation in C
Dynamic Memory Allocation in C
Vijayananda Ratnam Ch
 
Pointers and Memory Allocation ESC101.pptx
Pointers and Memory Allocation ESC101.pptxPointers and Memory Allocation ESC101.pptx
Pointers and Memory Allocation ESC101.pptx
krishna50blogging
 
dynamicmemoryallocation.pptx
dynamicmemoryallocation.pptxdynamicmemoryallocation.pptx
dynamicmemoryallocation.pptx
Niharika606186
 
Pointer
PointerPointer
Pointer
manish840
 
13. dynamic allocation
13. dynamic allocation13. dynamic allocation
13. dynamic allocation웅식 전
 
PPT DMA.pptx
PPT  DMA.pptxPPT  DMA.pptx
Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Dynamic Memory Allocation, Pointers and Functions, Pointers and StructuresDynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Selvaraj Seerangan
 
16858 memory management2
16858 memory management216858 memory management2
16858 memory management2Aanand Singh
 
ADK COLEGE.pptx
ADK COLEGE.pptxADK COLEGE.pptx
ADK COLEGE.pptx
Ashirwad2
 
Dynamic Memory Allocation
Dynamic Memory AllocationDynamic Memory Allocation
Dynamic Memory Allocation
vaani pathak
 

Similar to PF UE LEC 7 Pointers programming fundamentals (2).pptx (20)

Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptx
 
(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings
 
Dynamic Memory allocation
Dynamic Memory allocationDynamic Memory allocation
Dynamic Memory allocation
 
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
 
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
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
dynamic-allocation.pdf
dynamic-allocation.pdfdynamic-allocation.pdf
dynamic-allocation.pdf
 
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
 
dynamicmemoryallocation.pptx
dynamicmemoryallocation.pptxdynamicmemoryallocation.pptx
dynamicmemoryallocation.pptx
 
Pointer
PointerPointer
Pointer
 
13. dynamic allocation
13. dynamic allocation13. dynamic allocation
13. dynamic allocation
 
PPT DMA.pptx
PPT  DMA.pptxPPT  DMA.pptx
PPT DMA.pptx
 
Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Dynamic Memory Allocation, Pointers and Functions, Pointers and StructuresDynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
 
16858 memory management2
16858 memory management216858 memory management2
16858 memory management2
 
ADK COLEGE.pptx
ADK COLEGE.pptxADK COLEGE.pptx
ADK COLEGE.pptx
 
Dynamic Memory Allocation
Dynamic Memory AllocationDynamic Memory Allocation
Dynamic Memory Allocation
 

Recently uploaded

Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
Mohammed Sikander
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
JEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questionsJEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questions
ShivajiThube2
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
kimdan468
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 

Recently uploaded (20)

Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
JEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questionsJEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questions
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 

PF UE LEC 7 Pointers programming fundamentals (2).pptx

  • 1. Programming Fundamentals Lecture 9 Dynamic memory allocation in C and in C++, dangling pointer, memory leak
  • 2. Dynamic memory allocation • Dynamic memory allocation in C/C++ refers to performing memory allocation manually by programmer. • The most important use is flexibility provided to programmers. We are free to allocate and deallocate memory whenever we need and whenever we don’t need anymore.
  • 3. Dynamic memory allocation • For normal variables like “int a”, “char str[10]”, etc, memory is automatically allocated and deallocated. For dynamically allocated memory it is programmers responsibility to deallocate memory when no longer needed.
  • 4. malloc- C function supported in C++ • “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. • ptr = (cast-type*) malloc(byte-size) • ptr = (int*) malloc(100 * sizeof(int)); • Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory. • Header file: cstdlib
  • 5. int main() { // This pointer will hold the base address of the block created int* ptr; int n, i, sum = 0; // Get the number of elements for the array cin>>n; // Dynamically allocate memory using malloc() ptr = (int*)malloc(n * sizeof(int)); // Check if the memory has been successfully allocated by malloc or not if (ptr == NULL) { cout<<"Memory not allocated.n"; exit(); } else { // Memory has been successfully allocated cout<<"Memory successfully allocated using malloc.n“; // Get the elements of the array for (i = 0; i < n; ++i) { ptr[i] = i + 1; } // Print the elements of the array cout<<"The elements of the array are: "; for (i = 0; i < n; ++i) { cout<<ptr[i]; } } return 0; }
  • 6. Calloc • “calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type. It initializes each block with a default value ‘0’. • ptr = (cast-type*)calloc(n, element-size); • ptr = (float*) calloc(25, sizeof(float)); • This statement allocates contiguous space in memory for 25 elements each with the size of the float
  • 7. free • “free” method in C is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() is not de- allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it. • free(ptr);
  • 8. realloc • “realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory. In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re- allocate memory. • ptr = realloc(ptr, newSize); where ptr is reallocated with new size 'newSize'. // use: taking array size again from user in a program
  • 9. new operator • The new operator denotes a request for memory allocation. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable. pointer-variable = new data-type; int *p = NULL; p = new int; int *p = new int;
  • 10. Initialize the memory • pointer-variable = new data-type(value); • Example: int *p = new int(25); float *q = new float(75.25);
  • 11. Allocate block of memory • new operator is also used to allocate a block(an array) of memory of type data-type. • pointer-variable = new data-type[size]; • Example: int *p = new int[10] Dynamically allocates memory for 10 integers continuously of type int and returns pointer to the first element of the sequence, which is assigned to p(a pointer). p[0] refers to first element, p[1] refers to second element and so on.
  • 12. delete operator • // Release memory pointed by pointer-variable delete pointer-variable; • Here, pointer-variable is the pointer that points to the data object created by new. delete p; To free the dynamically allocated array pointed by pointer-variable, use following form of delete: // Release block of memory pointed by pointer-variable delete[] pointer-variable; Example: // It will free the entire array pointed by p. delete[] p;
  • 13. // C++ program to illustrate dynamic allocation // and deallocation of memory using new and delete #include <iostream> using namespace std; int main () { // Pointer initialization to null int* p = NULL; // Request memory for the variable using new operator p = new int; if (p==NULL) cout << "allocation of memory failedn"; else { // Store value at allocated address *p = 29; cout << "Value of p: " << *p << endl; } // Request block of memory using new operator float *r = new float(75.25); cout << "Value of r: " << *r << endl; // Request block of memory of size n int n = 5; int *q = new int[n]; if (q==NULL) cout << "allocation of memory failedn"; else { for (int i = 0; i < n; i++) q[i] = i+1; cout << "Value store in block of memory: "; for (int i = 0; i < n; i++) cout << q[i] << " "; } // freed the allocated memory delete p; delete r; // freed the block of allocated memory delete[] q; return 0; }
  • 14. Dangling pointer • A situation when a pointer points to the memory location of the deallocated memory. It is important to make a pointer NULL after de- allocating its allocated memory. • Example of that situation could be when two pointers pointing to same memory location and one deallocates that memory.
  • 15. Memory leak • A memory leak occurs in C++ when you allocate memory dynamically and never give it back. • The memory leak occurs, when a piece of memory which was previously allocated by the programmer. Then it is not deallocated properly by programmer. That memory is no longer in use by the program. So that place is reserved for no reason. That’s why this is called the memory leak. • For the memory leak, some block of memory may have wasted. If the system has enough memory, in that case also this may slow down the performance.
  • 16. References • C++ How to Program By Deitel & Deitel • The C++ Programming Language By Bjarne Stroustrup • Object oriented programming using C++ by Tasleem Mustafa, Imran Saeed, Tariq Mehmood, Ahsan Raza • https://www.tutorialspoint.com/cplusplus • http://ecomputernotes.com/cpp/introduction-to-oop • http://www.cplusplus.com/doc/tutorial • http://www.c4learn.com/c-programming/c-dangling-pointer-causes/ • https://www.guru99.com/c-loop-statement.html • www.w3schools.com • https://www.geeksforgeeks.org/