SlideShare a Scribd company logo
Memory Management
System Programing BSCS
Introduction
• Since C is a structured language, it has some fixed rules for
programming. One of them includes changing the size of an
array. An array is a collection of items stored at contiguous
memory locations.
Dynamic Memory Allocation in C
• If there is a situation where only 5 elements are needed to be
entered in this array. In this case, the remaining 4 indices are
just wasting memory in this array. So there is a requirement to
lessen the length (size) of the array from 9 to 5.
• Take another situation. In this, there is an array of 9 elements
with all 9 indices filled. But there is a need to enter 3 more
elements in this array. In this case, 3 indices more are required.
So the length (size) of the array needs to be changed from 9 to
12.
Dynamic Memory Allocation in C
• Dynamic Memory Allocation is a way through which the size of
data structure can be changed during execution (on run time).
• Memory assigned to a program in a typical architecture can be
divided into four segments.
• Code
• Static/ Global Variables.
• Stack
• heap
The Process’s Memory
• Each process has its own virtual address space dynamically translated into
physical memory address space by the MMU (and the kernel.)
• This space is divided in several part,
• A stack where local and volatile data are stored,
• Global variables and an unorganized space for program’s data called the heap.
• The heap is a continuous (in term of virtual addresses) space of memory
with three bounds:
• a starting point
• a maximum limit (managed through sys/ressource.h’s functions getrlimit(2) and
setrlimit(2))
• End point called the break.
• The break marks the end of the mapped memory space, that is, the part of
the virtual address space that has correspondence into real memory.
Family of stdlib.h
• Dynamic memory allocation could be achieved by using four
functions:
• malloc()
• calloc()
• free()
• realloc()
malloc
• Malloc( ) stands for memory allocation
• It reserves a block of memory with the given amount of bytes.
• The return value is a void pointer to the allocated space
• Therefore the void pointer needs to be casted to appropriate type as
per the requirement.
• However, if the space is insufficient, allocation of memory fails and
returns a NULL pointer.
• All the values at allocated memory are initialized to garbage values
Syntax of malloc
ptr = (cast-type*) malloc(byte-size)
For Example:
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.
• If space is insufficient, allocation fails and returns a NULL
pointer.
#include <stdio.h>
#include <stdlib.h>
int main()
{ int* ptr;
int n, i;
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %dn", n);
ptr = (int*)malloc(n * sizeof(int));
if (ptr == NULL) { printf("Memory not allocated.n"); exit(0); }
else {
printf("Memory successfully allocated using malloc.n");
for (i = 0; i < n; ++i) { ptr[i] = i + 1; }
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); }
} return 0;
}
brk(2) and sbrk(2)
• brk(2) place the break at the given address addr and return 0 if
successful, -1 otherwise. The global errno symbol indicate the nature
of the error.
int brk(const void *addr );
• sbrk(2) move the break by the given increment (in bytes.) Depending
on system implementation, it returns the previous or the new break
address. On failure, it returns (void *)-1 and set errno.
void* sbrk(intptr_t incr );
• On some system sbrk accepts negative values (in order to free some
mapped memory.)
The Process’s Memory..
In order to code a malloc, we need to know where the heap begin and the
break position, and of course we need to be able to move the break. This the
purpose of the two syscalls brk and sbrk.
Calloc()
• Calloc() stands for Contiguous allocation
• It reserves n blocks of memory with the given amount of bytes
• The return value is a void pointer to the allocated space
• Therefore the void pointer needs to be casted to the appropriate type
as per the requirments
• However, if the space is sufficient, allocation of memory fails and it
return a null pointer.
• All the values at allocated memory are initialized to 0
• Systanx:
• Prt = (ptr-type*) calloc (n, size_in_bytes)
Realloc()
• realloc() stands for reallocation
• If the dynamically allocated memory is insufficient we can change the
size of the pervious allocated memory using realloc () function
• Syntax:
• Ptr = (ptr-type*) realloc (ptr, new_size_in_bytes)
Free()
• Free() is used to free the allocated memory
• If the dynamically allocated memory is not required anymore, we can
free it using free function
• This will free the memory being used by the program in the heap
• Syntax:
• free(ptr)
Difference between malloc() and calloc()
S.No. malloc() calloc()
1. malloc() function creates a single
block of memory of a specific size.
calloc() function assigns multiple blocks of
memory to a single variable.
2. The number of arguments in malloc()
is 1.
The number of arguments in calloc() is 2.
3. malloc() is faster. calloc() is slower.
4. malloc() has high time efficiency. calloc() has low time efficiency.
5. The memory block allocated by
malloc() has a garbage value.
The memory block allocated by calloc() is
initialized by zero.
6. malloc() indicates memory allocation. calloc() indicates contiguous allocation.

More Related Content

Similar to Memory Management.pptx

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 in C
Dynamic Memory Allocation in CDynamic Memory Allocation in C
Dynamic Memory Allocation in C
Vijayananda Ratnam Ch
 
dynamic_v1-3.pptx
dynamic_v1-3.pptxdynamic_v1-3.pptx
dynamic_v1-3.pptx
ngonidzashemutsipa
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Viji B
 
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
 
dynamicmemoryallocation.pptx
dynamicmemoryallocation.pptxdynamicmemoryallocation.pptx
dynamicmemoryallocation.pptx
Niharika606186
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Gem WeBlog
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
Sabaunnisa3
 
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
helpme43
 
C dynamic ppt
C dynamic pptC dynamic ppt
C dynamic ppt
RJ Mehul Gadhiya
 
Dynamic memory Allocation in c language
Dynamic memory Allocation in c languageDynamic memory Allocation in c language
Dynamic memory Allocation in c language
kiran Patel
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in c
lavanya marichamy
 
(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.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptx
ssuser688516
 
Advance topics of C language
Advance  topics of C languageAdvance  topics of C language
Advance topics of C language
Mehwish Mehmood
 
Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)
Kamal Acharya
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Mohammad Usman
 
C- language Lecture 6
C- language Lecture 6C- language Lecture 6
C- language Lecture 6
Hatem Abd El-Salam
 
Introduction to Data Structures, Data Structures using C.pptx
Introduction to Data Structures, Data Structures using C.pptxIntroduction to Data Structures, Data Structures using C.pptx
Introduction to Data Structures, Data Structures using C.pptx
poongothai11
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
UTTAM VERMA
 

Similar to Memory Management.pptx (20)

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 in C
Dynamic Memory Allocation in CDynamic Memory Allocation in C
Dynamic Memory Allocation in C
 
dynamic_v1-3.pptx
dynamic_v1-3.pptxdynamic_v1-3.pptx
dynamic_v1-3.pptx
 
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
 
dynamicmemoryallocation.pptx
dynamicmemoryallocation.pptxdynamicmemoryallocation.pptx
dynamicmemoryallocation.pptx
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
 
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
 
C dynamic ppt
C dynamic pptC dynamic ppt
C dynamic ppt
 
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
 
(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.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptx
 
Advance topics of C language
Advance  topics of C languageAdvance  topics of C language
Advance topics of C language
 
Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
C- language Lecture 6
C- language Lecture 6C- language Lecture 6
C- language Lecture 6
 
Introduction to Data Structures, Data Structures using C.pptx
Introduction to Data Structures, Data Structures using C.pptxIntroduction to Data Structures, Data Structures using C.pptx
Introduction to Data Structures, Data Structures using C.pptx
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 

Recently uploaded

MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
Basic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparelBasic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparel
top1002
 
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERSCW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
veerababupersonal22
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
aqil azizi
 
Steel & Timber Design according to British Standard
Steel & Timber Design according to British StandardSteel & Timber Design according to British Standard
Steel & Timber Design according to British Standard
AkolbilaEmmanuel1
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
ChristineTorrepenida1
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
ssuser7dcef0
 
Fundamentals of Induction Motor Drives.pptx
Fundamentals of Induction Motor Drives.pptxFundamentals of Induction Motor Drives.pptx
Fundamentals of Induction Motor Drives.pptx
manasideore6
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
gestioneergodomus
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 

Recently uploaded (20)

MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
Basic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparelBasic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparel
 
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERSCW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
 
Steel & Timber Design according to British Standard
Steel & Timber Design according to British StandardSteel & Timber Design according to British Standard
Steel & Timber Design according to British Standard
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
 
Fundamentals of Induction Motor Drives.pptx
Fundamentals of Induction Motor Drives.pptxFundamentals of Induction Motor Drives.pptx
Fundamentals of Induction Motor Drives.pptx
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 

Memory Management.pptx

  • 2. Introduction • Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations.
  • 3. Dynamic Memory Allocation in C • If there is a situation where only 5 elements are needed to be entered in this array. In this case, the remaining 4 indices are just wasting memory in this array. So there is a requirement to lessen the length (size) of the array from 9 to 5. • Take another situation. In this, there is an array of 9 elements with all 9 indices filled. But there is a need to enter 3 more elements in this array. In this case, 3 indices more are required. So the length (size) of the array needs to be changed from 9 to 12.
  • 4. Dynamic Memory Allocation in C • Dynamic Memory Allocation is a way through which the size of data structure can be changed during execution (on run time). • Memory assigned to a program in a typical architecture can be divided into four segments. • Code • Static/ Global Variables. • Stack • heap
  • 5. The Process’s Memory • Each process has its own virtual address space dynamically translated into physical memory address space by the MMU (and the kernel.) • This space is divided in several part, • A stack where local and volatile data are stored, • Global variables and an unorganized space for program’s data called the heap. • The heap is a continuous (in term of virtual addresses) space of memory with three bounds: • a starting point • a maximum limit (managed through sys/ressource.h’s functions getrlimit(2) and setrlimit(2)) • End point called the break. • The break marks the end of the mapped memory space, that is, the part of the virtual address space that has correspondence into real memory.
  • 6. Family of stdlib.h • Dynamic memory allocation could be achieved by using four functions: • malloc() • calloc() • free() • realloc()
  • 7. malloc • Malloc( ) stands for memory allocation • It reserves a block of memory with the given amount of bytes. • The return value is a void pointer to the allocated space • Therefore the void pointer needs to be casted to appropriate type as per the requirement. • However, if the space is insufficient, allocation of memory fails and returns a NULL pointer. • All the values at allocated memory are initialized to garbage values
  • 8. Syntax of malloc ptr = (cast-type*) malloc(byte-size) For Example: 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. • If space is insufficient, allocation fails and returns a NULL pointer.
  • 9. #include <stdio.h> #include <stdlib.h> int main() { int* ptr; int n, i; printf("Enter number of elements:"); scanf("%d",&n); printf("Entered number of elements: %dn", n); ptr = (int*)malloc(n * sizeof(int)); if (ptr == NULL) { printf("Memory not allocated.n"); exit(0); } else { printf("Memory successfully allocated using malloc.n"); for (i = 0; i < n; ++i) { ptr[i] = i + 1; } printf("The elements of the array are: "); for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); } } return 0; }
  • 10. brk(2) and sbrk(2) • brk(2) place the break at the given address addr and return 0 if successful, -1 otherwise. The global errno symbol indicate the nature of the error. int brk(const void *addr ); • sbrk(2) move the break by the given increment (in bytes.) Depending on system implementation, it returns the previous or the new break address. On failure, it returns (void *)-1 and set errno. void* sbrk(intptr_t incr ); • On some system sbrk accepts negative values (in order to free some mapped memory.)
  • 11. The Process’s Memory.. In order to code a malloc, we need to know where the heap begin and the break position, and of course we need to be able to move the break. This the purpose of the two syscalls brk and sbrk.
  • 12. Calloc() • Calloc() stands for Contiguous allocation • It reserves n blocks of memory with the given amount of bytes • The return value is a void pointer to the allocated space • Therefore the void pointer needs to be casted to the appropriate type as per the requirments • However, if the space is sufficient, allocation of memory fails and it return a null pointer. • All the values at allocated memory are initialized to 0 • Systanx: • Prt = (ptr-type*) calloc (n, size_in_bytes)
  • 13. Realloc() • realloc() stands for reallocation • If the dynamically allocated memory is insufficient we can change the size of the pervious allocated memory using realloc () function • Syntax: • Ptr = (ptr-type*) realloc (ptr, new_size_in_bytes)
  • 14. Free() • Free() is used to free the allocated memory • If the dynamically allocated memory is not required anymore, we can free it using free function • This will free the memory being used by the program in the heap • Syntax: • free(ptr)
  • 15. Difference between malloc() and calloc() S.No. malloc() calloc() 1. malloc() function creates a single block of memory of a specific size. calloc() function assigns multiple blocks of memory to a single variable. 2. The number of arguments in malloc() is 1. The number of arguments in calloc() is 2. 3. malloc() is faster. calloc() is slower. 4. malloc() has high time efficiency. calloc() has low time efficiency. 5. The memory block allocated by malloc() has a garbage value. The memory block allocated by calloc() is initialized by zero. 6. malloc() indicates memory allocation. calloc() indicates contiguous allocation.