0% found this document useful (0 votes)
6 views

DS Class 8-Dynamic Mem Alloc-AI&ML (2)

The document discusses dynamic memory allocation, which allows programs to allocate memory during execution using functions like malloc(), calloc(), realloc(), and free(). It contrasts dynamic memory allocation with static memory allocation, highlighting the advantages of flexibility and efficient memory management. Additionally, it provides examples and syntax for each function, as well as warnings about potential memory leaks if allocated memory is not properly freed.

Uploaded by

basavananda
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)
6 views

DS Class 8-Dynamic Mem Alloc-AI&ML (2)

The document discusses dynamic memory allocation, which allows programs to allocate memory during execution using functions like malloc(), calloc(), realloc(), and free(). It contrasts dynamic memory allocation with static memory allocation, highlighting the advantages of flexibility and efficient memory management. Additionally, it provides examples and syntax for each function, as well as warnings about potential memory leaks if allocated memory is not properly freed.

Uploaded by

basavananda
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/ 29

Dynamic Memory Allocation

Memory Allocation
Reserving/Allocating memory to the data used by a program using
variables
• Types of allocation
• Static Memory allocation : allocating memory at compilation time
• Dynamic memory allocation : allocating memory at execution time
Memory allocation functions
Memory allocation is the procedure of assigning the computer memory for the
execution of programs and processes.

• There are 2 types:


• Static Memory Allocation: If memory-space to be allocated for various variables is decided during
compilation-time itself, then the memory-space cannot be expanded to accommodate more data or
cannot be reduced to accommodate less data.

• In this method, once the size of the memory-space to be allocated is fixed, it cannot be altered
during execution-time. This is called static memory allocation. For ex, int a[5];
Dynamic Memory Allocation Functions
Dynamic memory allocation allows a program to obtain more memory space,

while running or to release space when no space is required.

There are 4 library functions under "stdlib.h" for dynamic memory allocation.
Dynamic memory allocation
• Dynamic memory allocation is the process of allocating memory-space
during execution-time i.e. run time. If there is an unpredictable storage
requirement, then the dynamic allocation technique is used.

• This allocation technique uses predefined functions to allocate and


release memory for data.

• Dynamic memory allocation allows a program to obtain more memory


space, while running or to release space when no space is required
during execution-time
Dynamic memory allocation
• Dynamic memory allocation: The process of allocating memory at run
time is called as dynamic memory allocation. In other words it the
process of allocating memory while the program is running.

• To allocate memory dynamically at run-time, the following functions


are used:
malloc()
calloc()
realloc()
free()
Dynamic memory allocations: malloc()-memory
allocation
 The name malloc stands for "memory allocation".
 malloc: The malloc function reserves a block of memory of specified size and returns a pointer of type
void *.

 The syntax is shown below:


data_type *p; // datatype of ponter
p=(data_type*)malloc(size); //explicit typecasting

 here p is pointer variable of data_type can be int, float or char, size is number of bytes to be allocated

 If we want dynamically allocated memory to be referred by a specific type, then we need to type cast
explicitly.

 If memory is successfully allocated, then address of the first byte of allocated space is returned. If
memory allocation fails, then NULL is returned.
malloc()-memory allocation
• Example :
• ptr=(int*)malloc(100*sizeof(int));

The above statement will allocate 200 bytes assuming sizeof(int)=2


bytes.
calloc(): contiguous allocation
• The name calloc stands for "contiguous(in sequence) allocation".

• malloc allocates a single block of memory, while calloc function allocates


multiple blocks of memory each of same size and then sets all bytes to
zero.

• The syntax is shown below:


• data_type *p;
• p=(data_type *)calloc(n,size);
• Here, n represents no of blocks of memory each of size, size-in-bytes.
calloc()
• If memory is successfully allocated, then address of the first byte of allocated space
is returned. If memory allocation fails, then NULL is returned.

• The allocated memory is initialized automatically to 0's.

• For ex:
ptr=(int*)calloc(25,sizeof(int));

• The above statement allocates contiguous space in memory for an array of 25


elements each of size of int, i.e., 2 bytes.
Example: Program to find sum of n elements entered by user. Allocate memory
dynamically using calloc() function.

#include <stdio.h>
#include <stdlib.h>
void main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: "); scanf("%d",&n);
ptr=(int*) calloc (n,sizeof(int));
printf("Enter element s of array: ");
for(i=0;i<n;++i)
Output:
{ Enter number of elements: 3
scanf("%d ",ptr+i); sum+=*(ptr+i); Enter elements of array: 2 5 1
Sum= 8
}
printf("Sum=%d",sum); free(ptr);
}
Differences between malloc() and calloc()
realloc()

• The memory allocated using malloc or calloc can be modified with the
help of function realloc()

• If the previously allocated memory is insufficient or more than


sufficient. Then, you can change memory-size previously allocated
using realloc().

The syntax is shown below:


• ptr=(data_type*)realloc(ptr,newsize);
realloc()

• For example, if original allocation of memory is done by the following statement:


int *p;
p = (int *) malloc (size);
Then reallocation is done by,
p = realloc(p,newSize)

The above statement, changes the size of the memory block pointed by p to
newSize. The newSize may be larger or smaller than size.
Example: Program to illustrate working of realloc().
#include <stdio.h>
#include <stdlib.h>
void main()
{
int *ptr, i, n1, n2;
printf("Enter size of array: "); scanf("%d",&n1);
ptr=(int*)malloc(n1*sizeof(int));
printf("Address of previously allocated memory: ");
for(i=0;i<n1;i++)
printf("%u \n", ptr+i);
printf("\n Enter new size of arra y: ");
scanf("%d",&n2);
ptr= realloc (ptr,n2);
printf("Address of newly allocated memory: ");
for(i=0;i<n2;i++)
printf("%u \n", ptr+i);
}
free()
•To free the block of memory that was allocated using malloc or calloc
can be released using free function.

The syntax is: free(ptr);


• Here, ptr is a pointer that points to the dynamically allocated
memory.

For example consider the following code:


int ptr;
ptr = (int *) calloc(int);
free(ptr);
Representation of Linear Array in
memory
Let LA be a Linear Array

LOC(LA[K])=Base(LA)+w(K-lower bound)
Where w is the number of words(register size)per memory cell for the array LA
1000 1

1002 2

1004 3

1006 4
Example:
Consider the array AUTO which records number of automobiles sold each year
from 1932 through 1984. Suppose AUTO appears in memory as pictured in the
figure below:
200 AUTO[1932]
201
202
203
204 AUTO[1933]
205
206
207
208 AUTO[1934]
209
210
211
200 AUTO[1932] Base[AUTO]=200
201 w=4 words per memory cell
202 Then LOC(AUTO[1932])=200
203 LOC(AUTO[1933])=204
204 AUTO[1933] LOC(AUTO[1934])=208
205 -----------------
206 -----------------
207 Address of the array element for the year k=1965 can be
208 AUTO[1934] obtained by using equation
209
210 LOC(LA[k])=Base(LA)+w(k-lower bound)
211
LOC(AUTO[1965])=Base[AUTO]+4(1965-1932)
=200+4(33)
=332
Dynamically Allocated arrays
#include <stdio.h>
#include <stdlib.h>
#include <alloc.h>
void main()
{
int n,i,*list;
printf("Enter number of elements: "); scanf("%d",&n);
list=(int*) malloc (n*sizeof(int));
if(list==NULL) { printf(“insufficient memory”); exit(0); }
printf("Enter elements of the Array: ");
for(i=0;i<n;++i)
{
scanf("%d",list+i);
}
printf("elements are: ");
for(i=0;i<n;++i)
{
printf("%d ",*(list+i));
}
free(list);
malloc( )
•The function malloc allocates a
user- specified amount of memory
and a pointer to the start of the
allocated memory is returned.
•If there is insufficient memory to
make the allocation, the returned
value is NULL. Syntax: Where, data_type *x;
x= (data_type *) malloc(size); x is a pointer
variable of data_type
size is the number of bytes
Ex: int *ptr; ptr = (int *)
malloc(100*sizeof(int));
calloc( )
• The function calloc allocates a user-specified amountof memory and
initializes the allocated memory to 0 and a pointer to the start of the allocated memory
is returned.
• If there is insufficient memory to make the allocation, the returned value is NULL.

• Syntax:
Where,
data_type *x; Example:
x= int *x
(data_type *) x= calloc (10, sizeof(int));
calloc(n, The above example is used to
size); define a one-dimensional array of
integers. The capacity of this array
x is a pointer
is n=10 and x [0: n-1] (x [0, 9]) are
variable of
initially 0
type int
realloc(
)
 Before using the realloc( ) function, the memory should have been allocated using
malloc( ) or calloc( ) functions.
 The function relloc( ) resizes memory previously allocated by either malloc or calloc,
which means, the size of the memory changes by extending or deleting the allocated
memory.
 If the existing allocated memory need to extend, the pointer value will not change.
 If the existing allocated memory cannot be extended, the function allocates a new block
and copies the contents of existing memory block into new memory block and then
deletes the old memory block.
 When realloc is able to do the resizing, it returns a pointer to the start of the new block
and when it is unable to do the resizing, the old block is unchanged and the function
returns the value NULL
• Syntax:
data_type *x;
x= (data_type *) realloc(p, s );
free(
)
• Dynamically allocated memory with either malloc( ) or calloc ( ) does
not return on its own. The programmer must use free( ) explicitly to
release space.
Syntax:
free(ptr);
• This statement cause the space in memory pointer by ptr to
be deallocated
Memory leak
Memory leak occurs when programmers create a memory in heap and
forget to delete it.
/* Function with memory leak */
#include <stdlib.h>
void f()
{
int *ptr = (int *) malloc(sizeof(int));
/* Do some work */
return; /* Return without freeing ptr*/
}
Memory leak
To avoid memory leaks, memory allocated on heap should always be
freed when no longer needed.
/* Function without memory leak */
#include <stdlib.h>;
void f()
{
int *ptr = (int *) malloc(sizeof(int));
/* Do some work */
free(ptr);
return;
}

You might also like