Following presentation gives the brief view about dynamic memory allocation used for allocating space at runtime.
Go through the slides hope it will be helpful to get the basic knowledge about the dynamic memory allocation.
Please comment and shares your views.
1. Dynamic Memory Allocation
Active Learning Assessment
Semester:2
Computer Programming Utilization(2110003)
Made By:- Burhanuddin Kapadia Submitted to:- Prof. Parin Patel
Enrolment:- 170120119026
Branch:- Mechanical Department
3. Introduction
C language requires numbers of elements in an array to be specified at compile time.
Many languages permit a programmer to specify an arrays size at run time.
Such language have the ability to calculate and assign, during execution, the memory
space required by the variables in a program.
The process of allocating memory at run time is known as Dynamic Memory Allocation.
C program have four routine library for memory allocation and freeing space.
i. Malloc
ii. Calloc
iii. Free
iv. realloc
Their performance varies in both execution time and required memory.
5. Malloc
A block of memory is allocated by malloc
Allocates single block of requested memory.
It doesn't initialize memory at execution time, so it has
garbage value initially.
Allocates specified number of bytes
Returns NULL if memory is not sufficient.
Syntax of malloc():
𝒗𝒐𝒊𝒅 ∗ 𝒎𝒂𝒍𝒍𝒐𝒄 𝒔𝒊𝒛𝒆 − 𝒕 𝒏 ;
Can be written as:-
𝒑𝒕𝒓 = 𝒄𝒂𝒔𝒕 − 𝒕𝒚𝒑𝒆 ∗ 𝒎𝒂𝒍𝒍𝒐𝒄 𝒃𝒚𝒕𝒆 − 𝒔𝒊𝒛𝒆 ;
6. Calloc
Calloc is normally used for requesting memory space at run
time.
It stores data types such as arrays and structures.
Allocates multiple block of requested memory.
Calloc allocates memory to hold 30 records.
Allocates specified numbers of bytes.
Initially initialize all bytes to zero.
syntax of calloc():
𝒗𝒐𝒊𝒅 ∗ 𝒄𝒂𝒍𝒍𝒐𝒄 𝒔𝒊𝒛𝒆 − 𝒕 𝒏, 𝒔𝒊𝒛𝒆 − 𝒕 𝒔𝒊𝒛𝒆 ;
Can be written as:
𝒑𝒕𝒓 = 𝒄𝒂𝒔𝒕 − 𝒕𝒚𝒑𝒆 ∗ 𝒄𝒂𝒍𝒍𝒐𝒄 𝒏, 𝒆𝒍𝒆𝒎 − 𝒔𝒊𝒛𝒆 ;
7. Malloc() Calloc()
The name malloc stands
for memory allocation.
Takes only one argument
Amount of memory is in
bytes
Does not initialize the
memory allocated
The name calloc stands
for contiguous allocation
Takes two argument
Amount of memory of single
variable in numbers of
variable
Guarantees that all the bytes
of allocated memory block
have been initialized to 0
Difference between malloc & calloc
8. Programs for malloc & calloc
/* Allocate memory for an int. */
int *ptr = (int*) malloc(sizeof
(int));
if (ptr == NULL)
{
printf("Could not allocate
memoryn");
exit(-1);
}
else
printf("Memory allocated
successfully.n");
/* Allocating memory for an array
of 10 elements of type int. */
int *ptr = (int*) calloc(10 ,sizeof (int));
if (ptr == NULL)
{
printf("Could not allocate
memoryn");
exit(-1);
}
else
printf("Memory allocated
successfully.n");