0% found this document useful (0 votes)
10 views37 pages

Chapter 3 DMA (Dynamic Memory Allocation)

The document outlines a course on Problem Solving with Programming, focusing on dynamic memory allocation in C. It details course objectives, outcomes, evaluation schemes, and provides an introduction to dynamic memory allocation, including functions like malloc, calloc, and realloc. Additionally, it compares static and dynamic memory allocation, discusses memory management, and includes frequently asked questions and references for further study.

Uploaded by

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

Chapter 3 DMA (Dynamic Memory Allocation)

The document outlines a course on Problem Solving with Programming, focusing on dynamic memory allocation in C. It details course objectives, outcomes, evaluation schemes, and provides an introduction to dynamic memory allocation, including functions like malloc, calloc, and realloc. Additionally, it compares static and dynamic memory allocation, discusses memory management, and includes frequently asked questions and references for further study.

Uploaded by

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

INSTITUTE - UIE

DEPARTMENT- ACADEMIC UNIT-2

Bachelor of Engineering (Computer Science & Engineering)


Subject Name: Problem solving with programming

Code:20CST111
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
CONTENTS

• Introduction to DMA
• Examples

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

6
DYNAMIC MEMORY ALLOCATION(DMA)
As you know, you have to declare the size of an array before you use it.
Hence, the array you declared may be insufficient or more than
required to hold data. To solve this issue, you can allocate memory
dynamically.
Dynamic memory management refers to manual memory
management. This allows you to obtain more memory when required
and release it when not necessary.
Although C inherently does not have any technique to allocate memory
dynamically, there are 4 library functions defined under <stdlib.h> for
dynamic memory allocation.

7
Standard DMA Functions

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

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

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


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

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

18
19
20
21
22
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.

23
24
25
26
Difference between Stack and 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

Heap Space not used as efficiently. Memory can


Space managed efficiently by OS so memory will
Space management become fragmented as blocks of memory first
never become fragmented.
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.

27
Automatically done by compiler It is manually done by the
Allocation and Deallocation
instructions. programmer.

Does not require to de-allocate


Deallocation Explicit de-allocation is needed.
variables.

Cost Less More

A stack can be implemented in 3


ways simple array based, using Heap can be implemented using
Implementation
dynamic memory, and Linked list array and trees.
based.

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

28
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
memory allocation function Realloc is used to reallocate
stands for memory allocation
that allocates multiple memory according to the
that blocks of memory with
memory blocks at a time specified size.
the specific size initialized to
initialized to 0
a garbage value

Free function is used to clear


the dynamically allocated
memory.

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

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

31
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
32
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);
33
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);

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

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

35
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:
1. https://www.guru99.com/c-dynamic-memory-allocation.html
2. https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/
3. https://www.programiz.com/c-programming/c-dynamic-memory-allocation
4. https://www.guru99.com/stack-vs-
heap.html#:~:text=Stack%20is%20a%20linear%20data,you%20to%20access%20variables%20globally.
5. https://www.learn-
c.org/en/Dynamic_allocation#:~:text=To%20allocate%20a%20new%20person,to%20the%20newly%20allocated%20data.
6. https://www.programiz.com/c-programming/examples/structure-dynamic-memory-allocation
7. https://aticleworld.com/dynamically-allocate-2d-array-c/

8. https://www.geeksforgeeks.org/dynamically-allocate-2d-array-c/

YouTube Links:
1. https://www.youtube.com/watch?v=v49bwqQ4ouM&t=11s
2. https://www.youtube.com/watch?v=669YaQQMM_0&list=PLiOa6ike4WAEH5k7DB_lOLVrJ1Rq3fTNe
3. https://www.youtube.com/watch?v=udfbq4M2Kfc
4. https://www.youtube.com/watch?v=1oE5-NrI_Zo

36
THANK YOU

You might also like