Lecture 3.3.1 Dynamic Memory Allocation and Functions.pptx
1.
DISCOVER . LEARN. EMPOWER
Dynamic Memory Allocation
UNIVERSITY INSTITUTE OF ENGINEERING
DEPARTMENT- ACADEMIC UNITS
FIRST YEAR ENGINEERING PROGRAMMES
Subject Name : Introduction to Problem Solving
Subject Code: 24CSH-101
2.
Introduction to
Problem Solving
CourseObjectives
2
The course aims to provide exposure to problem-
solving through programming.
The course aims to raise the programming skills
of students via logic building capability.
With knowledge of C programming language,
students would be able to model real world
problems.
3.
3
CO
Number
Course Outcome
CO1 Rememberthe concepts related to fundamentals of C language,
draw flowcharts and write algorithm/pseudocode.
CO2 Understand the way of execution and debug programs in C
language.
CO3 Apply various constructs, loops, functions to solve mathematical
and scientific problem.
CO4 Analyze the dynamic behavior of memory by the use of pointers.
CO5 Design and develop modular programs for real world problems
using control structure and selection structure.
Course
Outcomes
4.
4
ASSESSMENT PATTERN
The performanceof students is evaluated as follows:
Theory Practical
Components
Continuous Internal
Assessment (CAE)
Semester End
Examination (SEE)
Continuous Internal
Assessment (CAE)
Semester End
Examination (SEE)
Marks 40 60 60 40
Total Marks 100 100
5.
5
• Dynamic MemoryAllocation is manual allocation and freeing of memory according
to your programming needs.
• Dynamic memory is managed and served with pointers that point to the newly
allocated memory space in an area which we call the heap.
• Now you can create and destroy an array of elements dynamically at runtime without
any problems.
• To sum up, the automatic memory management uses the stack, and the dynamic
memory allocation uses the heap.
Introduction to Dynamic Memory allocation
6.
6
Difference between Stackand Heap
Parameter Stack Heap
Type of data structures A stack is a linear data structure. Heap is a hierarchical data structure.
Access speed High-speed access Slower compared to stack
Space management
Space managed efficiently by OS so memory will
never become fragmented.
Heap Space not used as efficiently. Memory can
become fragmented as blocks of memory first
allocated and then freed.
Access Local variables only It allows you to access variables globally.
Limit of space size Limit on stack size dependent on OS. Does not have a specific limit on memory size.
Resize Variables cannot be resized Variables can be resized.
Memory Allocation Memory is allocated in a contiguous block. Memory is allocated in any random order.
7.
7
Allocation and Deallocation
Automaticallydone by compiler
instructions.
It is manually done by the
programmer.
Deallocation
Does not require to de-allocate
variables. Explicit de-allocation is needed.
Cost Less More
Implementation
A stack can be implemented in 3
ways simple array based, using
dynamic memory, and Linked list
based.
Heap can be implemented using
array and trees.
Main Issue Shortage of memory Memory fragmentation
Locality of reference Automatic compile time instructions. Adequate
Flexibility Fixed size Resizing is possible
Access time Faster Slower
8.
8
Static Memory Allocationand Dynamic Memory Allocation
Static Memory Allocation Dynamic Memory Allocation
Memory is allocated at compile time. Memory is allocated at run time.
Memory can't be increased while executing program. Memory can be increased while executing program.
Used in array. Used in linked list.
9.
9
Standard DMA Functions
FunctionPurpose
malloc Allocates the memory of requested size and
returns the pointer to the first byte of allocated
space.
calloc Allocates the space for elements of an array.
Initializes the elements to zero and returns a
pointer to the memory.
realloc It is used to modify the size of previously allocated
memory space.
Free Frees or empties the previously allocated memory
space.
10.
10
The malloc Function
•The malloc() function stands for memory allocation.
• It is a function which is used to allocate a block of memory
dynamically.
• It reserves memory space of specified size and returns the null
pointer pointing to the memory location.
• The pointer returned is usually of type void. It means that we can
assign malloc function to any pointer.
11.
11
Syntax:
ptr = (cast_type*) malloc (byte_size);
Here,
ptr is a pointer of cast_type.
The malloc function returns a pointer to the allocated memory of
byte_size.
Example:
ptr = (int *) malloc (50)
When this statement is successfully executed, a memory space of 50
bytes is reserved. The address of the first byte of reserved space is
assigned to the pointer ptr of type int.
12.
12
Consider another example:
#include<stdlib.h>
int main(){
int *ptr;
ptr = malloc(15 * sizeof(*ptr)); /* a block of 15 integers */
if (ptr != NULL) {
*(ptr + 5) = 480; /* assign 480 to sixth integer */
printf("Value of the 6th integer is %d",*(ptr + 5));
}
}
Output:
Value of the 6th integer is 480
13.
13
1.Notice that sizeof(*ptr)was used instead of sizeof(int) in order to make the code
more robust when *ptr declaration is typecasted to a different data type later.
2.The allocation may fail if the memory is not sufficient. In this case, it returns a NULL
pointer. So, you should include code to check for a NULL pointer.
3.Keep in mind that the allocated memory is contiguous and it can be treated as an
array. We can use pointer arithmetic to access the array elements rather than using
brackets [ ]. We advise to use + to refer to array elements because using incrementation
++ or += changes the address stored by the pointer.
Malloc function can also be used with the character data type as well as complex data
types such as structures.
14.
14
The calloc Function
•The calloc function stands for contiguous allocation.
• This function is used to allocate multiple blocks of memory.
• It is a dynamic memory allocation function which is used to allocate
the memory to complex data structures such as arrays and structures.
• Malloc function is used to allocate a single block of memory space
while the calloc function is used to allocate multiple blocks of
memory space.
• Each block allocated by the calloc function is of the same size.
15.
15
• Syntax:
ptr =(cast_type *) calloc (n, size);
• 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.
16.
16
• Whenever thereis an error allocating memory space such as the
shortage of memory, then a null pointer is returned.
• The program below calculates the sum of an arithmetic sequence.
#include <stdio.h>
int main() {
int i, * ptr, sum = 0;
ptr = calloc(10, sizeof(int));
if (ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
17.
17
printf("Building and calculatingthe sequence sum of the first 10 terms n ");
for (i = 0; i < 10; ++i) { * (ptr + i) = i;
sum += * (ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
Result:
Building and calculating the sequence sum of the first 10 terms
Sum = 45
18.
18
Difference between Callocand Malloc
• The calloc function is generally more suitable and efficient
than that of the malloc function.
• While both the functions are used to allocate memory space,
calloc can allocate multiple blocks at a single time.
• You don't have to request for a memory block every time.
• The calloc function is used in complex data structures which
require larger memory space.
• The memory block allocated by a calloc function is always
initialized to zero while in malloc it always contains a garbage
value.
19.
19
The realloc Function
•Using the realloc() function, you can add more memory size to already
allocated memory.
• It expands the current block while leaving the original content as it is.
• realloc stands for reallocation of memory.
• realloc can also be used to reduce the size of the previously allocated
memory.
20.
20
Syntax:
ptr = realloc(ptr,newsize);
• The above statement allocates a new memory space with a specified
size in the variable newsize.
• After executing the function, the pointer will be returned to the first
byte of the memory block.
• The new size can be larger or smaller than the previous memory.
• We cannot be sure that if the newly allocated block will point to the
same location as that of the previous memory block.
• This function will copy all the previous data in the new region.
• It makes sure that data will remain safe.
21.
21
For example:
#include <stdio.h>
intmain () {
char *ptr;
ptr = (char *) malloc(10);
strcpy(ptr, "Programming");
printf(" %s, Address = %un", ptr, ptr);
ptr = (char *) realloc(ptr, 20); //ptr is reallocated with new size
strcat(ptr, " In 'C'");
printf(" %s, Address = %un", ptr, ptr);
free(ptr);
return 0;
}
• Whenever the realloc results in an unsuccessful operation, it returns a null pointer, and the
previous data is also freed.
22.
22
The free Function
•The memory for variables is automatically deallocated at
compile time.
• In dynamic memory allocation, you have to deallocate
memory explicitly.
• If not done, you may encounter out of memory error.
• The free() function is called to release/deallocate memory.
• By freeing memory in your program, you make more
available for use later.
23.
23
For example:
#include <stdio.h>
intmain() {
int* ptr = malloc(10 * sizeof(*ptr));
if (ptr != NULL){
*(ptr + 2) = 50;
printf("Value of the 2nd integer is %d",*(ptr + 2));
}
free(ptr);
}
Output
Value of the 2nd integer is 50
24.
24
Dynamically allocating memoryto 1-D array
• In the below example, we are creating a pointer to an integer and assign it heap memory.
• When memory is successfully assigned to the pointer then we can use this pointer as a 1D array and using
the square braces “[]” we can access the pointer as like the statically allocated array.
• Let us see the below Image for better understanding:
Source:https://aticleworld.com/dynamically-allocate-2d-array-c/
25.
25
#include <stdio.h>
#include <stdlib.h>
#defineFAIL 1
#define TRUE 0
int main()
{
int *p;//= NULL; //pointer to integer
int n= 7; //can be dynamic input as well.
int i = 0; //Variable for looping
p = (int *)malloc(n * sizeof(int));
//Check memory validity
if(p == NULL)
{
return FAIL;
}
for (i =0; i < n; i++)
{
p[i] = i;
}
//Print the copy data
for (i=0; i< n; i++)
{
printf("np[%d] = %dn", i,p[i]);
}
// free allocated memory
free(p);
return TRUE;
}
27
Dynamically allocating memoryto 2-D array
Following are different ways to create a 2D array on heap (or dynamically allocate a 2D array).
In the following examples, we have considered ‘r‘ as number of rows, ‘c‘ as number of columns and we created a 2D
array with r = 3, c = 4 and following values
1 2 3 4
5 6 7 8
9 10 11 12
1) Using a single pointer:
A simple way is to allocate memory block of size r*c and access elements using simple pointer arithmetic.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int r = 3, c = 4;
int *arr = (int *)malloc(r * c * sizeof(int));
int i, j, count = 0;
28.
28
for (i =0; i < r; i++)
for (j = 0; j < c; j++)
*(arr + i*c + j) = ++count;
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
printf("%d ", *(arr + i*c + j));
/* Code for further processing and free the
dynamically allocated memory */
free(arr);
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10 11 12
29.
29
2) Using anarray of pointers
We can create an array of pointers of size r. Note that from C99, C language allows variable sized arrays. After
creating an array of pointers, we can dynamically allocate memory for every row.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int r = 3, c = 4, i, j, count;
int *arr[r];
for (i=0; i<r; i++)
arr[i] = (int *)malloc(c * sizeof(int));
// Note that arr[i][j] is same as *(*(arr+i)+j)
count = 0;
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
*(*(arr+i)+j) = ++count ; //OR arr[i][j] = ++count;
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
printf("%d ", *(*(arr+i)+j) );
/* Code for further processing and free the
dynamically allocated memory */
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10 11 12
30.
30
3) Using pointerto a pointer
We can create an array of pointers also dynamically using a double pointer. Once we have an array pointers allocated
dynamically, we can dynamically allocate memory and for every row like method 2.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int r = 3, c = 4, i, j, count;
int **arr = (int **)malloc(r * sizeof(int *));
for (i=0; i<r; i++)
arr[i] = (int *)malloc(c * sizeof(int));
// Note that arr[i][j] is same as *(*(arr+i)+j)
count = 0;
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
arr[i][j] = ++count; // OR *(*(arr+i)+j) = ++count
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
printf("%d ", arr[i][j]);
/* Code for further processing and free the
dynamically allocated memory */
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10 11 12
31.
31
4) Using doublepointer and one malloc call
#include<stdio.h>
#include<stdlib.h>
int main()
{
int r=3, c=4, len=0;
int *ptr, **arr;
int count = 0,i,j;
len = sizeof(int *) * r + sizeof(int) * c * r;
arr = (int **)malloc(len);
// ptr is now pointing to the first element in of 2D array
ptr = (int *)(arr + r);
// for loop to point rows pointer to appropriate location in 2D array
for(i = 0; i < r; i++)
arr[i] = (ptr + c * i);
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
arr[i][j] = ++count; // OR *(*(arr+i)+j) = ++count
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
printf("%d ", arr[i][j]);
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10 11 12
32.
32
Dynamically allocating memoryto structure
• Let's assume we want to dynamically allocate a person structure. The person is defined like this:
typedef struct {
char * name;
int age;
} person;
• To allocate a new person in the myperson argument, we use the following syntax:
person * myperson = (person *) malloc(sizeof(person));
• This tells the compiler that we want to dynamically allocate just enough to hold a person struct in
memory, and then return a pointer to the newly allocated data.
• Note that sizeof is not an actual function, because the compiler interprets it and translates it to
the actual memory size of the person struct.
33.
33
• To accessthe person's members, we can use the -> notation:
myperson->name = "John";
myperson->age = 27;
• After we are done using the dynamically allocated struct, we can release it using
free:
free(myperson);
• Note that the free does not delete the myperson variable itself, it simply releases
the data that it points to.
• The myperson variable will still point to somewhere in the memory - but after
calling myperson we are not allowed to access that area anymore.
• We must not use that pointer again until we allocate new data using it.
34.
34
Example:
#include <stdio.h>
#include <stdlib.h>
structcourse {
int marks;
char subject[30];
};
int main() {
struct course *ptr;
int i, noOfRecords;
printf("Enter the number of records: ");
scanf("%d", &noOfRecords);
// Memory allocation for noOfRecords structures
ptr = (struct course *)malloc(noOfRecords * sizeof(struct course));
for (i = 0; i < noOfRecords; ++i) {
printf("Enter the name of the subject and marks respectively:n");
scanf("%s %d", (ptr + i)->subject, &(ptr + i)->marks);
}
printf("Displaying Information:n");
for (i = 0; i < noOfRecords; ++i)
printf("%st%dn", (ptr + i)->subject, (ptr + i)->marks);
return 0;
}
Output:
Enter the number of records: 2
Enter the name of the subject and marks respectively:
Programming
22
Enter the name of the subject and marks respectively:
Structure
33
Displaying Information:
Programming 22
Structure 33
35.
Advantages
• When wedo not know how much amount of memory would be needed for the
program beforehand.
• When we want data structures without any upper limit of memory space.
• When you want to use your memory space more efficiently.
• Example: If you have allocated memory space for a 1D array as array[20] and you end
up using only 10 memory spaces then the remaining 10 memory spaces would be
wasted and this wasted memory cannot even be utilized by other program variables.
• Dynamically created lists insertions and deletions can be done very easily just by the
manipulation of addresses whereas in case of statically allocated memory insertions
and deletions lead to more movements and wastage of memory.
• When you want you to use the concept of structures and linked list in programming,
dynamic memory allocation is a must.
35
36.
Disadvantages
• As thememory is allocated during runtime, it requires more time.
• Memory needs to be freed by the user when done. This is important
as it is more likely to turn into bugs that are difficult to find.
36
37.
37
Summary
In dynamic memory
allocation,memory is
allocated at a run time.
We can dynamically manage
memory by creating memory
blocks as needed in the heap
Dynamic memory allocation
permits to manipulate
strings and arrays whose size
is flexible and can be
changed anytime in your
program.
Calloc is a contiguous
memory allocation function
that allocates multiple
memory blocks at a time
initialized to 0
Malloc is a dynamic memory
allocation function which
stands for memory allocation
that blocks of memory with
the specific size initialized to
a garbage value
It is required when you have
no idea how much memory a
particular structure is going
to occupy.
Realloc is used to reallocate
memory according to the
specified size.
Free function is used to clear
the dynamically allocated
memory.
38.
38
Frequently Asked question
Q1What is the difference between malloc and calloc?
Ans. A malloc and calloc are memory management functions. They are used to allocate memory dynamically. Basically, there is
no actual difference between calloc and malloc except that the memory that is allocated by calloc is initialized with 0. In C
language,calloc function initialize the all allocated space bits with zero but malloc does not initialize the allocated memory.
These both function also has a difference regarding their number of arguments, malloc takes one argument but calloc takes two.
Q2 What is the purpose of realloc( )?
Ans. The realloc function is used to resize the allocated block of the memory. It takes two arguments first one is a pointer to
previously allocated memory and the second one is the newly requested size. The calloc function first deallocates the old object
and allocates again with the newly specified size. If the new size is lesser to the old size, the contents of the newly allocated
memory will be the same as prior but if any bytes in the newly created object goes beyond the old size, the values of the object
will be indeterminate.
Q3 What is the return value of malloc (0)?
Ans. If the size of the requested space is zero, the behavior will be implementation-defined. The return value of the malloc could
be a null pointer or it shows the behavior like that size is some nonzero value. So you must never use the malloc(0) in your C
program.
39.
39
Q4 What arethe return type of malloc() and calloc(), how can we use?
Ans. Malloc() and calloc() both functions return void* (a void pointer), to use/capture the returned value in
pointer variable we convert it's type.
Suppose we create memory for 10 integers then we have to convert it into int*.
int *ptr;
ptr=(int*)malloc(N*sizeof(int));
Here, malloc() will return void* and ptr variable is int* type, so we are converting it into (int*).
Q5 Explain free() unique features?
Ans. The free() function defined in <stdlib.h> header file deallocates the memory which was previously
allocated using malloc(), calloc() or realloc.
If free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed.
It helps to reduce wastage of memory by freeing it.
40.
40
Assessment Questions:
1. Pointout the error in the following program.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *a[3];
a = (int*) malloc(sizeof(int)*3);
free(a);
return 0;
}
A. Error: unable to allocate memory
B. Error: We cannot store address of allocated memory in a
C. Error: unable to free memory
D. No error
41.
41
2. malloc() allocatesmemory from the heap and not from the stack.
a) Yes
b) No
3. Point out the correct statement which correctly free the memory pointed to by 's' and 'p' in the following program?
#include<stdio.h>
#include<stdlib.h>
int main()
{
struct ex
{
int i;
float j;
char *s
};
struct ex *p;
p = (struct ex *)malloc(sizeof(struct ex));
p->s = (char*)malloc(20);
return 0;
}
A. free(p); , free(p->s);
B. free(p->s); , free(p);
C. free(p->s);
D. free(p);
42.
42
4. malloc() returnsa NULL if it fails to allocate the requested memory.
a) True
b) False
5. Which of the following statement is correct prototype of the malloc() function in c ?
a) int* malloc(int);
b) char* malloc(char);
c) unsigned int* malloc(unsigned int);
d) void* malloc(size_t);
43.
43
Discussion forum.
• Watchthis video to have more insights into the topic DMA.
https://www.youtube.com/watch?v=v49bwqQ4ouM
44.
44
REFERENCES
Reference Books
1. Programmingin C by Reema Thareja.
2. Programming in ANSI C by E. Balaguruswamy, Tata McGraw Hill.
3. Programming with C (Schaum's Outline Series) by Byron Gottfried Jitender Chhabra, Tata McGraw Hill.
4. The C Programming Language by Brian W. Kernighan, Dennis Ritchie, Pearson education.
Websites:
5. https://www.guru99.com/c-dynamic-memory-allocation.html
6. https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/
7. https
://www.guru99.com/stack-vs-heap.html#:~:text=Stack%20is%20a%20linear%20data,you%20to%20access%20variables
%20globally
.
8. https://www.learn-c.org/en/Dynamic_allocation#:~:text=To%20allocate%20a%20new%20person,to%20the%20newly%
20allocated%20data.
9. https://www.programiz.com/c-programming/examples/structure-dynamic-memory-allocation
10. https://aticleworld.com/dynamically-allocate-2d-array-c/
YouTube Links:
11. https://www.youtube.com/watch?v=v49bwqQ4ouM&t=11s
12. https://www.youtube.com/watch?v=669YaQQMM_0&list=PLiOa6ike4WAEH5k7DB_lOLVrJ1Rq3fTNe
13. https://www.youtube.com/watch?v=udfbq4M2Kfc
14. https://www.youtube.com/watch?v=1oE5-NrI_Zo