0% found this document useful (0 votes)
18 views24 pages

Chapter DMA

Uploaded by

muskan sangwan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views24 pages

Chapter DMA

Uploaded by

muskan sangwan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

INSTITUTE - UIE

DEPARTMENT- ACADEMIC UNIT-1

Bachelor of Engineering (Computer Science & Engineering)


Subject Name: Fundamentals of Computer Science

Code:20CST122
Unit-3

Dynamic Memory Allocation DISCOVER . LEARN . EMPOWER


Problem solving
with
programming
Course Objectives

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.
2
Course Outcomes
CO Title Level
Number

CO1 Identify​ situations where Understand


computational methods would
be useful.
CO2 Approach the programming tasks Remember
using techniques learnt and
write pseudo-code.
CO3 Choose the right data Understand
representation formats based on
the requirements of the
problem.
CO4 Use the comparisons and Understand
limitations of the various
programming constructs and
choose the right one for the task.

3
Scheme of Evaluation

Sr. Type of Assessment Weightage of actual Frequency of Task Final Weightage in Internal Remarks
No. Task conduct Assessment (Prorated
Marks)

1. Assignment* 10 marks of One Per Unit 10 marks As applicable to


each assignment course types depicted
above.
2. Time Bound 12 marks for each One per Unit 4 marks As applicable to
Surprise test course types
Test depicted above.
3. Quiz 4 marks of each quiz 2 per Unit 4marks As applicable to
course types
depicted above.
4. Mid-Semester Test** 20 marks for one 2 per semester 20 marks As applicable to
MST. course types
depicted above.
5. Presentation*** Non Graded: Engagement Only for Self Study
Task MNGCourses.

6. Homework NA One per lecture topic Non-Graded: Engagement As applicable to


(of 2 Task course types
questions) depicted above.
7. Discussion Forum NA One per Non Graded: Engagement As applicable to
Chapter Task course types depicted
above.
8. Attendance and NA NA 2 marks
Engagement Score
on BB
4
Introduction to Dynamic Memory
allocation
• Dynamic Memory Allocation 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.

5
Static Memory Allocation and 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.

6
Standard DMA Functions
Function Purpose
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.

7
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.

8
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.

9
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.

10
• 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.

11
Difference between Calloc and 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.

12
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.

13
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.

14
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.

15
Summary
Dynamic memory allocation
permits to manipulate
In dynamic memory We can dynamically manage
strings and arrays whose size
allocation, memory is memory by creating memory
is flexible and can be
allocated at a run time. blocks as needed in the heap
changed anytime in your
program.

Malloc is a dynamic memory


Calloc is a contiguous
allocation function which It is required when you have
memory allocation function
stands for memory allocation no idea how much memory a
that allocates multiple
that blocks of memory with particular structure is going
memory blocks at a time
the specific size initialized to to occupy.
initialized to 0
a garbage value

Realloc is used to reallocate Free function is used to clear


memory according to the the dynamically allocated
specified size. memory.

16
Frequently Asked question
Q1 What 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.

17
Q4 What are the 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.

18
Assessment Questions:
1. Point out 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
19
2. malloc() allocates memory 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);
20
4. malloc() returns a 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);

21
Discussion forum.
• Watch this video to have more insights into the topic DMA.

https://www.youtube.com/watch?v=v49bwqQ4ouM

22
Reference Books
REFERENCES
1. Programming in 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.programiz.com/c-programming/c-dynamic-memory-allocation
8. https://www.guru99.com/stack-vs-heap.html#:~:text=Stack%20is%20a%20linear%20data,you%20to%20access
%20variables%20globally
.
9. https://www.learn-c.org/en/Dynamic_allocation#:~:text=To%20allocate%20a%20new%20person,to%20the%20
newly%20allocated%20data.
10. https://www.programiz.com/c-programming/examples/structure-dynamic-memory-allocation
11. https://aticleworld.com/dynamically-allocate-2d-array-c/
12. https://www.geeksforgeeks.org/dynamically-allocate-2d-array-c/

YouTube Links:
13. https://www.youtube.com/watch?v=v49bwqQ4ouM&t=11s
14. https://www.youtube.com/watch?v=669YaQQMM_0&list=PLiOa6ike4WAEH5k7DB_lOLVrJ1Rq3fTNe
15. https://www.youtube.com/watch?v=udfbq4M2Kfc
16. https://www.youtube.com/watch?v=1oE5-NrI_Zo 23
THANK YOU

You might also like