SlideShare a Scribd company logo
Vijayananda Ratnam Ch,
Asst. Professor,
Dept. of CSE,
VVIT – Guntur.
Dynamic Memory Allocation in C
1
Introduction
2
 Memory management is one of the most fundamental and important aspect for
any computer programming language.
 In many programming language you don’t have to worry about the memory
management, but in C Programming Language you to do memory management
manually.
 C is one of the most powerful programming language. Pointer is one of the most
powerful feature of the C programming language which gives you the ability to
point memory locations. This feature enables you easy memory access.
 As we all know computer memory is made up of large number of cells. So it is
always necessary to manage these memory locations effectively to increase the
utilization.
 To allocate memory it is necessary to keep information available memory in the
system. If memory management system finds sufficient free memory, it allocates
only as much memory as needed, keeping the rest available to satisfy future
request.
Static or Compile time memory allocation
3
 In this method desired memory is allocated at the time of variable declaration or
beginning of the program.
 Amount of memory allocation is fixed and is determined at the time of program
compilation.
Example:
int a, b;
 When the first statement int a, b; is compiled 4 consecutive bytes for each
variable a, b will be allocated.
Drawbacks:
 If we declare more number of variables and we are using less number of
variables then the memory allocated for the unused variables will be wasted.
The unused memory cells are not made available to other applications. This
leads to inefficient use of memory.
 Size for the data type or variable must be know before.
 We can not change the size of variable at run time.
Dynamic or Runtime memory allocation
4
 In the dynamic memory allocation, the memory is allocated to a variable
or program at the run time.
 The only way to access this dynamically allocated memory is through
pointer.
 It makes efficient use of memory.
 C provides the following dynamic allocation and de-allocation functions –
1. malloc()
2. calloc()
3. realloc()
4. free()
 These library routines known as memory management functions are
used for allocating and freeing memory during execution of a program.
These functions are defined in stdlib.h header file.
 malloc, calloc and realloc is used for memory allocation and de-
allocation is achieved by the use of free function.
Stack and Heap
5
 When program is loaded into main memory is divided into 4
segments: Code, Data, Stack, Heap
 A Data segment contains the global and static variables.
 A Code segment contains the executable instructions.
 A Stack segment stores all auto variables/local variables.
Also each function call involves passing arguments from the
caller to callee. The callee may also declare variables.
Function parameters, return address and automatic local
variables are accommodated in a stack.
 Hence a stack is an area of memory for storing data
temporarily.
 Allocation and de-allocation of memory in this area is done
automatically.
Stack and Heap…
6
 Heap segment is for dynamic memory management.
 It is for the programmers to manage.
 We can allocate and deallocate memory when you feel the
need for it and delete when you feel that the memory is no
longer needed.
 C language supports a pair functions named malloc() and free()
to allocate and deallocate memory/space from heap
respectively.
malloc() function
7
 The malloc( ) function stands for memory allocation.
 The malloc() function allocates the memory at run time whenever
required.
 It allocates the memory of requested size and returns the pointer to the
first byte (base address) of allocated space or returns NULL if memory is
not sufficient ( failed to allocate).
 The pointer returned is usually of type void. It means that we can assign
malloc() function to any pointer.
 It doesn't initialize memory at execution time, so it has garbage value
initially.
 Syntax:
malloc( ) function…
8
 Let us understand the malloc() with the following code :
ptr = malloc(8); // allocates 8 bytes of memory
 Here ptr is a pointer variable and it allocates 8 bytes of memory. Here we have not defined
datatype of the variable and ptr is a void pointer now. It will now point to the first byte in
the allocated memory.
 If we need to make this pointer as integer then we need specify the type also while
allocating memory then each integer value will be stored at the interval of 4 bytes.
ptr = (int*)malloc(8); //returns integer pointer to ptr pointing to first byte of allocated
memory
ptr = (int*)malloc(10* sizeof(int));
//allocates memory sufficient for 10 integer values and returns integer pointer to ptr
malloc( ) function…
9
 Let us understand the malloc( ) function with the following example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr;
ptr = (int *)malloc(10 * sizeof(int)); /* a block of 15 integers */
if (ptr == NULL)
printf("Error: Out of memoryn");
else
{
*(ptr + 5) = 480; /* assign 480 to sixth integer */
printf("Value of the 6th integer is %d",*(ptr + 5));
}
free(ptr);
return 0;
}
free() function
10
 The free( ) function is used to release the memory allocated by using
malloc ( ) or calloc () function.
 It is always important to release the memory that is not in use, so it can be
used in future otherwise leads to memory leak.
 If you don’t free it, your program grows larger and eventually runs out of
memory!
 Syntax:
free (pointer_var_name);
 Example:
free (ptr);
calloc( ) function
11
 The calloc( ) function stands for contiguous allocation.
 The calloc() function is same malloc() except it is used to allocate multiple
blocks of memory and all blocks are initialized to zero.
 It is used to allocate the memory to complex data structures such as arrays and
structures.
Syntax:
ptr = (cast-type *) calloc(n, size_in_bytes);
 The above statement is used to allocate n memory blocks of the same size.
 After the memory space is allocated, then all the bytes are initialized to zero.
 The pointer which is currently at the first byte of the allocated memory space is
returned.
Example:
ptr = (int *) calloc(10, sizeof(int));  It allocates 10 memory blocks for storing 10
integers.
realloc( ) function
12
 realloc( ) stands for reallocation of memory.
 Using the realloc( ) function, you can add more memory to already
allocated memory.
 It expands the current block while leaving the original content as it is.
 realloc() can also be used to reduce the size of the previously allocated
memory.
 Syntax:
ptr = (cast-type *) realloc(ptr,new_size);
 Example:
ptr = (char *) realloc(ptr, 20);
 It allocates 20 new memory locations. We cannot be sure that if the newly
allocated block will point to the same location as that of the previous
realloc( ) function…
13
 Let us understand the realloc( ) function with the following example:
int main ( )
{
char *ptr;
ptr = (char *) malloc(10); //allocated 10 bytes of memory
strcpy(ptr, "Programming"); //copy the string to ptr
printf(" %s, Address = %un", ptr, ptr);
ptr = (char *) realloc(ptr, 20); //ptr is reallocated with new size 20
strcat(ptr, " In 'C' "); //concatenation
printf(" %s, Address = %un", ptr, ptr);
free(ptr);
return 0;
}
Array of pointers
14
 “Array of pointers” is an array of the pointer variables. It is also known as
pointer arrays.
 Suppose we need to create an array of floating numbers to store 100
elements. Then:
float *ptr[100]; //creates 100 float pointer variables.
 Another way to create dynamic array to store 100 float numbers
float *ptr;
ptr = (float *) malloc (100 * sizeof (float) ); //using malloc()
ptr = (float *) calloc (100, sizeof ( float ) ); //using calloc()
15
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n,i,*ptr;
printf("Enter number of elements: ");
scanf("%d",&n);
//memory allocated using calloc
ptr=(int*)malloc(n*sizeof(int));
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("nAddress are:n");
for(i=0;i<n;++i)
{
printf("Adress = %ut
Value=%dn",(ptr+i),*(ptr+i));
//sum+=*(ptr+i);
}
printf("nSum=%d",sum);
free(ptr);
return 0;
}
Pointers to structures
16
Questions?
17
1. WAP to find the largest number in an array using pointers?
2. WAP to sort the strings in alphabetical order using pointers
3. WAP to copy one string to another using pointers
4. WAP to reverse an array using pointers?
5. WAP to count the numbers of vowels in an array of characters
using pointers?
6. WAP to search an element in an array of "N" elements using
pointers?
18

More Related Content

What's hot

Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Viji B
 
Pointers in C
Pointers in CPointers in C
Pointers in C
Prabhu Govind
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in c
lavanya marichamy
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
sai tarlekar
 
Storage class
Storage classStorage class
Storage class
Joy Forerver
 
Enumerated data types in C
Enumerated data types in CEnumerated data types in C
Enumerated data types in C
Arpana shree
 
Pointers in c
Pointers in cPointers in c
Pointers in c
Mohd Arif
 
Arrays in c unit iii chapter 1 mrs.sowmya jyothi
Arrays in c unit iii chapter 1 mrs.sowmya jyothiArrays in c unit iii chapter 1 mrs.sowmya jyothi
Arrays in c unit iii chapter 1 mrs.sowmya jyothi
Sowmya Jyothi
 
Break and continue
Break and continueBreak and continue
Break and continue
Frijo Francis
 
File handling in C
File handling in CFile handling in C
File handling in C
Kamal Acharya
 
Variadic functions
Variadic functionsVariadic functions
Variadic functions
Koganti Ravikumar
 
detailed information about Pointers in c language
detailed information about Pointers in c languagedetailed information about Pointers in c language
detailed information about Pointers in c language
gourav kottawar
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Naveen Gupta
 
Dynamic Memory allocation
Dynamic Memory allocationDynamic Memory allocation
Dynamic Memory allocation
Grishma Rajput
 
File in C language
File in C languageFile in C language
File in C language
Manash Kumar Mondal
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
tanmaymodi4
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and Unions
Dhrumil Patel
 
Introduction to Array ppt
Introduction to Array pptIntroduction to Array ppt
Introduction to Array ppt
sandhya yadav
 
Microprocessor chapter 9 - assembly language programming
Microprocessor  chapter 9 - assembly language programmingMicroprocessor  chapter 9 - assembly language programming
Microprocessor chapter 9 - assembly language programming
Wondeson Emeye
 
11 lec 11 storage class
11 lec 11 storage class11 lec 11 storage class
11 lec 11 storage class
kapil078
 

What's hot (20)

Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in c
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Storage class
Storage classStorage class
Storage class
 
Enumerated data types in C
Enumerated data types in CEnumerated data types in C
Enumerated data types in C
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
Arrays in c unit iii chapter 1 mrs.sowmya jyothi
Arrays in c unit iii chapter 1 mrs.sowmya jyothiArrays in c unit iii chapter 1 mrs.sowmya jyothi
Arrays in c unit iii chapter 1 mrs.sowmya jyothi
 
Break and continue
Break and continueBreak and continue
Break and continue
 
File handling in C
File handling in CFile handling in C
File handling in C
 
Variadic functions
Variadic functionsVariadic functions
Variadic functions
 
detailed information about Pointers in c language
detailed information about Pointers in c languagedetailed information about Pointers in c language
detailed information about Pointers in c language
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Dynamic Memory allocation
Dynamic Memory allocationDynamic Memory allocation
Dynamic Memory allocation
 
File in C language
File in C languageFile in C language
File in C language
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and Unions
 
Introduction to Array ppt
Introduction to Array pptIntroduction to Array ppt
Introduction to Array ppt
 
Microprocessor chapter 9 - assembly language programming
Microprocessor  chapter 9 - assembly language programmingMicroprocessor  chapter 9 - assembly language programming
Microprocessor chapter 9 - assembly language programming
 
11 lec 11 storage class
11 lec 11 storage class11 lec 11 storage class
11 lec 11 storage class
 

Similar to Dynamic Memory Allocation in C

Dma
DmaDma
Dma
Acad
 
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
 
Stack & heap
Stack & heap Stack & heap
Stack & heap
Shajahan T S Shah
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptx
ssuser688516
 
Introduction to c part -3
Introduction to c   part -3Introduction to c   part -3
ADK COLEGE.pptx
ADK COLEGE.pptxADK COLEGE.pptx
ADK COLEGE.pptx
Ashirwad2
 
Dma
DmaDma
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
AkhilMishra50
 
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
Gem WeBlog
 
06 linked list
06 linked list06 linked list
06 linked list
Rajan Gautam
 
Memory Management.pptx
Memory Management.pptxMemory Management.pptx
Memory Management.pptx
BilalImran17
 
Memory management CP
Memory management  CPMemory management  CP
Memory management CP
Shubham Sinha
 
final GROUP 4.pptx
final GROUP 4.pptxfinal GROUP 4.pptx
final GROUP 4.pptx
ngonidzashemutsipa
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
Muhammed Thanveer M
 
DYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxDYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptx
LECO9
 
DYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptxDYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptx
SKUP1
 
interview questions.docx
interview questions.docxinterview questions.docx
interview questions.docx
SeoTechnoscripts
 
DS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxDS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docx
VeerannaKotagi1
 
C interview questions
C interview questionsC interview questions
C interview questions
Soba Arjun
 

Similar to Dynamic Memory Allocation in C (20)

Dma
DmaDma
Dma
 
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
 
Stack & heap
Stack & heap Stack & heap
Stack & heap
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptx
 
Introduction to c part -3
Introduction to c   part -3Introduction to c   part -3
Introduction to c part -3
 
ADK COLEGE.pptx
ADK COLEGE.pptxADK COLEGE.pptx
ADK COLEGE.pptx
 
Dma
DmaDma
Dma
 
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
 
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
 
06 linked list
06 linked list06 linked list
06 linked list
 
Memory Management.pptx
Memory Management.pptxMemory Management.pptx
Memory Management.pptx
 
Memory management CP
Memory management  CPMemory management  CP
Memory management CP
 
final GROUP 4.pptx
final GROUP 4.pptxfinal GROUP 4.pptx
final GROUP 4.pptx
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
 
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
 
interview questions.docx
interview questions.docxinterview questions.docx
interview questions.docx
 
DS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxDS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docx
 
C interview questions
C interview questionsC interview questions
C interview questions
 

Recently uploaded

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
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
Celine George
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
What is the purpose of studying mathematics.pptx
What is the purpose of studying mathematics.pptxWhat is the purpose of studying mathematics.pptx
What is the purpose of studying mathematics.pptx
christianmathematics
 
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
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
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
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
NelTorrente
 
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
 

Recently uploaded (20)

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)
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
What is the purpose of studying mathematics.pptx
What is the purpose of studying mathematics.pptxWhat is the purpose of studying mathematics.pptx
What is the purpose of studying mathematics.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
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
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
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
 
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
 

Dynamic Memory Allocation in C

  • 1. Vijayananda Ratnam Ch, Asst. Professor, Dept. of CSE, VVIT – Guntur. Dynamic Memory Allocation in C 1
  • 2. Introduction 2  Memory management is one of the most fundamental and important aspect for any computer programming language.  In many programming language you don’t have to worry about the memory management, but in C Programming Language you to do memory management manually.  C is one of the most powerful programming language. Pointer is one of the most powerful feature of the C programming language which gives you the ability to point memory locations. This feature enables you easy memory access.  As we all know computer memory is made up of large number of cells. So it is always necessary to manage these memory locations effectively to increase the utilization.  To allocate memory it is necessary to keep information available memory in the system. If memory management system finds sufficient free memory, it allocates only as much memory as needed, keeping the rest available to satisfy future request.
  • 3. Static or Compile time memory allocation 3  In this method desired memory is allocated at the time of variable declaration or beginning of the program.  Amount of memory allocation is fixed and is determined at the time of program compilation. Example: int a, b;  When the first statement int a, b; is compiled 4 consecutive bytes for each variable a, b will be allocated. Drawbacks:  If we declare more number of variables and we are using less number of variables then the memory allocated for the unused variables will be wasted. The unused memory cells are not made available to other applications. This leads to inefficient use of memory.  Size for the data type or variable must be know before.  We can not change the size of variable at run time.
  • 4. Dynamic or Runtime memory allocation 4  In the dynamic memory allocation, the memory is allocated to a variable or program at the run time.  The only way to access this dynamically allocated memory is through pointer.  It makes efficient use of memory.  C provides the following dynamic allocation and de-allocation functions – 1. malloc() 2. calloc() 3. realloc() 4. free()  These library routines known as memory management functions are used for allocating and freeing memory during execution of a program. These functions are defined in stdlib.h header file.  malloc, calloc and realloc is used for memory allocation and de- allocation is achieved by the use of free function.
  • 5. Stack and Heap 5  When program is loaded into main memory is divided into 4 segments: Code, Data, Stack, Heap  A Data segment contains the global and static variables.  A Code segment contains the executable instructions.  A Stack segment stores all auto variables/local variables. Also each function call involves passing arguments from the caller to callee. The callee may also declare variables. Function parameters, return address and automatic local variables are accommodated in a stack.  Hence a stack is an area of memory for storing data temporarily.  Allocation and de-allocation of memory in this area is done automatically.
  • 6. Stack and Heap… 6  Heap segment is for dynamic memory management.  It is for the programmers to manage.  We can allocate and deallocate memory when you feel the need for it and delete when you feel that the memory is no longer needed.  C language supports a pair functions named malloc() and free() to allocate and deallocate memory/space from heap respectively.
  • 7. malloc() function 7  The malloc( ) function stands for memory allocation.  The malloc() function allocates the memory at run time whenever required.  It allocates the memory of requested size and returns the pointer to the first byte (base address) of allocated space or returns NULL if memory is not sufficient ( failed to allocate).  The pointer returned is usually of type void. It means that we can assign malloc() function to any pointer.  It doesn't initialize memory at execution time, so it has garbage value initially.  Syntax:
  • 8. malloc( ) function… 8  Let us understand the malloc() with the following code : ptr = malloc(8); // allocates 8 bytes of memory  Here ptr is a pointer variable and it allocates 8 bytes of memory. Here we have not defined datatype of the variable and ptr is a void pointer now. It will now point to the first byte in the allocated memory.  If we need to make this pointer as integer then we need specify the type also while allocating memory then each integer value will be stored at the interval of 4 bytes. ptr = (int*)malloc(8); //returns integer pointer to ptr pointing to first byte of allocated memory ptr = (int*)malloc(10* sizeof(int)); //allocates memory sufficient for 10 integer values and returns integer pointer to ptr
  • 9. malloc( ) function… 9  Let us understand the malloc( ) function with the following example: #include <stdio.h> #include <stdlib.h> int main() { int *ptr; ptr = (int *)malloc(10 * sizeof(int)); /* a block of 15 integers */ if (ptr == NULL) printf("Error: Out of memoryn"); else { *(ptr + 5) = 480; /* assign 480 to sixth integer */ printf("Value of the 6th integer is %d",*(ptr + 5)); } free(ptr); return 0; }
  • 10. free() function 10  The free( ) function is used to release the memory allocated by using malloc ( ) or calloc () function.  It is always important to release the memory that is not in use, so it can be used in future otherwise leads to memory leak.  If you don’t free it, your program grows larger and eventually runs out of memory!  Syntax: free (pointer_var_name);  Example: free (ptr);
  • 11. calloc( ) function 11  The calloc( ) function stands for contiguous allocation.  The calloc() function is same malloc() except it is used to allocate multiple blocks of memory and all blocks are initialized to zero.  It is used to allocate the memory to complex data structures such as arrays and structures. Syntax: ptr = (cast-type *) calloc(n, size_in_bytes);  The above statement is used to allocate n memory blocks of the same size.  After the memory space is allocated, then all the bytes are initialized to zero.  The pointer which is currently at the first byte of the allocated memory space is returned. Example: ptr = (int *) calloc(10, sizeof(int)); It allocates 10 memory blocks for storing 10 integers.
  • 12. realloc( ) function 12  realloc( ) stands for reallocation of memory.  Using the realloc( ) function, you can add more memory to already allocated memory.  It expands the current block while leaving the original content as it is.  realloc() can also be used to reduce the size of the previously allocated memory.  Syntax: ptr = (cast-type *) realloc(ptr,new_size);  Example: ptr = (char *) realloc(ptr, 20);  It allocates 20 new memory locations. We cannot be sure that if the newly allocated block will point to the same location as that of the previous
  • 13. realloc( ) function… 13  Let us understand the realloc( ) function with the following example: int main ( ) { char *ptr; ptr = (char *) malloc(10); //allocated 10 bytes of memory strcpy(ptr, "Programming"); //copy the string to ptr printf(" %s, Address = %un", ptr, ptr); ptr = (char *) realloc(ptr, 20); //ptr is reallocated with new size 20 strcat(ptr, " In 'C' "); //concatenation printf(" %s, Address = %un", ptr, ptr); free(ptr); return 0; }
  • 14. Array of pointers 14  “Array of pointers” is an array of the pointer variables. It is also known as pointer arrays.  Suppose we need to create an array of floating numbers to store 100 elements. Then: float *ptr[100]; //creates 100 float pointer variables.  Another way to create dynamic array to store 100 float numbers float *ptr; ptr = (float *) malloc (100 * sizeof (float) ); //using malloc() ptr = (float *) calloc (100, sizeof ( float ) ); //using calloc()
  • 15. 15 #include<stdio.h> #include<stdlib.h> int main() { int n,i,*ptr; printf("Enter number of elements: "); scanf("%d",&n); //memory allocated using calloc ptr=(int*)malloc(n*sizeof(int)); if(ptr==NULL) { printf("Sorry! unable to allocate memory"); exit(0); } printf("Enter elements of array: "); for(i=0;i<n;++i) { scanf("%d",ptr+i); sum+=*(ptr+i); } printf("nAddress are:n"); for(i=0;i<n;++i) { printf("Adress = %ut Value=%dn",(ptr+i),*(ptr+i)); //sum+=*(ptr+i); } printf("nSum=%d",sum); free(ptr); return 0; }
  • 17. Questions? 17 1. WAP to find the largest number in an array using pointers? 2. WAP to sort the strings in alphabetical order using pointers 3. WAP to copy one string to another using pointers 4. WAP to reverse an array using pointers? 5. WAP to count the numbers of vowels in an array of characters using pointers? 6. WAP to search an element in an array of "N" elements using pointers?
  • 18. 18