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");