Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Dynamic Memory Allocation: UNIT-1

You are on page 1of 44

UNIT-1

DYNAMIC MEMORY ALLOCATION


Introduction
Most often we face situations in programming where the data is dynamic in nature.
That is, the number of data items keeps changing during execution of the program. For
example, consider a program for processing the list of customers of a corporation .The
list grows when names are added and shrinks when names are deleted. When list
grows we need to allocate more memory space to the list to accommodate additional
data items. Such situations can be handled more easily and effectively by using
dynamic data structures in conjunction with dynamic memory management
techniques.

Dynamic data structures provide flexibility in adding , deleting or rearranging data


items at run time.Dynamic memory management techniques permit us to allocate
additional memory space or to release unwanted space at run time, thus ,optimizing
the use of storage space.

1. What is dynamic memory allocation?Explain memory allocation in C using


memory Map. (10 marks).

2.1 Dynamic memory allocation


C language requires the number of elements in array to be specified at compile time. But we
may not be able to do so always.

Many languages permit a programmer to specify an array’s size at run time. Such languages
have the ability to calculate and assign, during execution, the memory space required by the
variables in the program.

The process of allocating memory at runtime is known as dynamic memory allocation.


Library routines known as memory management functions are used for allocating and freeing
memory during execution of a program. These functions are defined in stdlib.h.

Function Description
malloc() Allocates requested size of bytes and returns a void pointer pointing to
the first byte of allocated space.
calloc() Allocates the space for an array element’s, initializes them to zero and
then returns a void pointer to the memory.
realloc() Modify the size of previously allocated space.
free() Release previously allocated memory.
Memory allocation process

Local variables

Free memory

Global variables

C program
instructions

Storage of c program

The program instructions, global and static variables are stored in a region known as
permanent storage area and the local variables are stored in another area called stack.
The memory space that is located between these two regions is available for dynamic
allocation during execution of the program. This free memory region is called the
heap. The size of the heap keeps changing when program is executed due to creation
and death of variables that are local to functions and blocks. Therefore, it is possible to
encounter memory overflow during dynamic allocation process. In such situations, the
memory allocation functions returns NULL pointer.

2. How to allocate a block of memory? Explain with an example.(10 marks)

OR

Explain allocating a block of using malloc(). (5 marks)

Allocating a block of memory: MALLOC


 A block of memory can be allocated using the function malloc.
 The malloc() function reserves a block of memory of specified size and returns
a pointer of type void. This means that we can assign it to any type of pointer.
 malloc() does not initialize the memory allocated during the execution. It
carries garbage value
Syntax:

pointer variable=(cast-type*)malloc(byte-size);

Pointer variable is of a type cast- type. The malloc returns a pointer to an area of
memory with size byte-size.
Example:

x=(int)malloc(100*sizeof(int));

The above example allocates 100 times the size of an integer bytes is reserved and the
address of the first byte of the memory allocated is assigned to the pointer of x of type
int.

Similarly, the statement

cptr=(char*)malloc(10);

allocates 10 bytes of space for the cptr of the type char.

We can also use malloc() to allocate space for complex data types such as structures.

Example: st_var=(struct store*)malloc(size of(struct store));

Where st_var is a pointer of type struct store.

Program to find sum of integers using malloc()

#include<stdio.h>

#include<stdlib.h>

void main()

int *ptr,sum=0,*a;

int n;

printf(“Enter how many elements you want to store\n”);

scanf(“%d”,&n);

ptr=(int*)malloc(n*sizeof(int));/*allocates memory dynamically the allocated memory


is n times the size of an integer.*/

if(ptr==NULL) //Allocation fails due to insufficient space in heap

printf(“\n Error in allocating memory\n”);

exit(0);

}
printf(“Enter the elements one by one\n”);

for(a=ptr;a<ptr+n;a++)//reading elements into an array

scanf(“%d”,a);

printf(“Elements of array are\n”);

for(a=ptr;a<ptr+n;a++)//Displays elements of an array

printf(“%d”,*a);

for(a=ptr;a<ptr+n;a++)//Finding sum of all the elemnts

sum=sum+a;

printf(“sum=%d”,sum);//Display the sum of all the elements

OUTPUT:

Enter the number of elements you want to store

Enter the elements one by one

10

20

30

40

50

Elements of array are:


10

20

30

40

50

Sum=150

The above illustrates the sum of n numbers in an array. Here the memory allocation is
done using malloc (). The allocated memory is equal to the n times the size of an
integer.

If the memory allocation fails due to the insufficient space in heap ,malloc () function
returns NULL otherwise the variable ptr contains the address of the first byte of the
allocated memory.

The values are read one by to the location which is pointed by ptr .The value of ptr is
assigned to another pointer variable ‘a’ .Values are read from into the address of the
first location till (p+n-1)th location’s address .Each time the value of the pointer is
incremented by scalar factor. Value pointed by the pointer ‘ptr’ is made to pointed by
the pointer ‘a’. These values are added till (p+n-1)th location. Finally the value of sum
is displayed.

3. With an example explain how to allocate multiple block of memory (10 marks)

OR

Explain calloc () with an example.

Allocating the multiple blocks of memory: CALLOC


calloc() is used for requesting memory space at run time for storing derived data types
such as arrays and structures. While malloc() allocates a single block of memory of
storage space , calloc allocates multiple blocks of storage, each of the same size and
then sets all bytes to zero.

The general form/ syntax of calloc is:

pointer_variable=(cast-type *)calloc(n,elem-size);

The above statement allocates contiguous space for n blocks, each of size elem-size
bytes. All bytes are initialized to zero.
Parameter:

It takes two parameters one is the value n ,which the number of elements for which
you want to allocate memory and elem-size is the size of each element in bytes.

Return value: On success a pointer to the first byte of the allocated region is
returned. If there is no enough space, a NULL is returned.

Example:

p=(int *)calloc(5,sizeof(int));

In the above example 5 blocks of memory is allocated each of size 2 bytes .Assuming
an integer occupies 2 bytes of memory. It returns void pointer by default it is
converted integer pointer as the type of pointer variable p is integer.

Example:

#include<stdio.h>

void main()

int *p,*a;

int n;

printf(“Enter the number of elements for which you want to allocate memory\n”);

scanf(“%d”,&n);

a=(int*)calloc(n,sizeof(int));

printf(“Enter the elements one by one\n”);

for(p=a;p<a+n;p++)

scanf(“%d”,p);

printf(“Elements of array are:\n”);

for(p=a;p<a+n;p++)

printf(“%d\n”,*p);

for(p=a;p<a+n;p++)

{
if(*p%2==0)

printf(“%d is even\n”,*p);

else

printf(“%d is odd\n”,*p);

free(p);

OUTPUT:

Enter the number of elements for which you want to allocate memory

Enter the elements one by one

Elements of array are:

2 is even

3 is odd

5 is odd

4 is even

The above example shows the memory allocation using calloc().The function calloc()
allocates memory dynamically, the allocated memory is 5 block each of the size 2
bytes. The address of the first block of the allocated memory is stored in a pointer
variable a.

Using loop n values are read into a pointer variable. Each time it is incremented by
one so that it points to the next location.

Each values are accessed from the address of the first block till the address of the

p+n-1 blocks. When each block is accessed its values are checked to find whether the
number is even or odd.

calloc() can be also used to allocate memory space for structure. Here the memory is
allocated for the individual memory of structure using number of records you want to
store and the size of the structure.

int s_size=5;

ptr=(stu*)calloc(s_size,sizeof(stu));

In the above example pointer ptr is of type structure tag name. It allocates total block
which is equal to the number of records you are storing and each of the size stu.

Example:

Allocating memory for structure using calloc()

#include<stdio.h>

#include<stdlib.h>
struct student

char name[10];

float tmarks;

int regno

};

typedef struct student stu;

stu *ptr;

void main()

{
int s_size;

stu ptr;

printf(“Enter how many record you want to store?\n”0;

scanf(“%d”,&s_size);

ptr=(stu*)calloc(s_size,sizeof(stu));

if(ptr==NULL)

printf(“memory allocation failed\n”);

exit(0);

printf(“Enter each student record\n”);

for(i=0;i<s_size;i++)

scanf(“%s%d%f”,p->name,&(p->marks),&(p->regno));

printf(“details of student are:\n”);

for(i=0;i<s_size;i++)

printf(“%s%d%f”,p->name,p->marks),p->regno);

Releasing the used space : FREE


4. How to release the previously allocated memory?

OR

Explain free().What are its advantages. (05 marks)

When a variable is allocated space during the compile time, then the memory used by
that variable is automatically released by the system in accordance with its storage
class. But when we dynamically allocate memory then it is our responsibility to
release the space when it is not required. This is even more important when the
storage space is limited. Therefore, if we no longer need the data stored in a particular
block of memory then it is our responsibility to release that block for storing any other
information, then as a good programming practice we must release that block of
memory for future use, using the free function.

General form:

free(pointer variable);

Pointer variable is a pointer that has been created by using malloc() or calloc().When
the memory is released using the free, it is returned back to the free list within heap.

When the memory is released using free:

i) It is not the pointer that is being released but rather what it points to.
ii) To release an array of memory that was allocated by calloc() we need only
to release the pointer once. It is an error to attempt to release elements
individually.

Example:

/*Program to copy the content of one string to another string*/

#include<stdio.h>

#include<stdlib.h>

void main()

char *str,*str1;

str=(char*)malloc(10*sizeof(char));

str1=(char*)calloc(10,sizeof(char));

if(str==NULL)

printf(“memory could not be allocated\n”);

exit(0);

printf(“Enter first string\n”);

gets(str);

strcpy(str1,str);
printf(“content of str is %s”,str);

printf(“Content of str1 is %s\n”,str1);

free(str);

free(str1);

OUTPUT:

Enter the first string

allocation

content of str is: allocation

content of str1 is: allocation

In the above example ,10 memory locations are allocated using malloc for the string
str each of the size one byte. The string str contains the address of the first byte of the
allocated space. Also for the memory is allocated for the destination string str1 using
calloc() total 10 blocks of memory is allocated and each of the size 1 byte.The string
str1 contains the address of the first block of the allocated memory in bytes.Both the
function returns NULL if there is insufficient memory .

User enters a string from the console, which is pointed by the pointer str. Content of
str is copied to str1 using string copy function strcpy().

At the end content of both the files are displayed and allocated memory for the string
str and str1 is released using free ().

Advantages of free():

Altering the size of allocated memory:realloc()


5. How to reallocate the previously allocated memory? Explain with an example?

OR

How to alter the memory size dynamically? Explain with an example.

At the times memory allocated by using calloc() or malloc() might be insufficient or in


excess. In both the situations we can always use realloc() to change the memory size
already allocated by calloc() and malloc().This process is called reallocation of
memory.

The function realloc() reallocates a memory block with a specified new size.If you call
realloc() the size of the memory block pointed to by the pointer is changed to the
given size in bytes.This way you are able to expand and reduce the amount of memory
you want to use.

It is possible that the function moves the meory block to anew location, in which the
function will return new location.

If the size of the requested block is larger then the previous block then the value of the
new portion is intermediate.

If the pointer is NULL then the function will behave exactly like the function
malloc().It will assign a new block of a size in bytes and will return a pointer to it.If
the size is zero then the memory that was previously allocated is freeds or if a call to
the function free()was given it returns a NULL pointer in that case.

Syntax:

(cast type*)realloc(pointer variable,newsize);

Parameter: This function takes two parameter one is pointer and another one is new
size.

A pointer variable to a previously allocated block of memory.

A new size in bytes for the new memory block.

Return value: Will return a pointer to the reallocated memory block.If the function
fails then a NULL pointer is returned.

Example:

(int *)realloc(ptr,30);
Using realloc we are changing the size of the memory .ptr is a pointer variable which
is pointing to the previously allocated memory using malloc() or calloc().The size of
the allocated block is changed to 30 which is a new size for the memory after realloc.

Example:

#include<stdio.h>

#include<stdlib.h>

void main()

char *buffer;

printf(“Enter the size\n”);

scanf(“%d”,&n);

buffer=(char *)malloc(n,sizeof(int));

if(p==NULL)

printf(“cannot allocate memory\n”);

exit(0);

printf(“buffer of size %d created \n”,_msize(buffer));

strcpy(buffer,”data”);

printf(“\n buffer contains:%s\n”,buffer);

buffer=(char*)realloc(buffer,15);

if(buffer==NULL)

printf(“reallocation failed\n”);

exit(0);

}
printf(“Buffer size modified\n”);

printf(“\n buffer still contains : %s\n”,buffer);

strcpy(buffer,”structure”);

printf(“\n Buffer now contains:%s\n”,buffer);

free(buffer);

Output:

Buffer of size 10 created

Buffer contains: data

Buffer size modified

Buffer still contains: data

Buffer now contains: structure

The above example illustrates the use of realloc() for changing the allocated memory
during run time.At the beginning memory is allocated using malloc().We can also
allocate using realloc().It return NULL if there is insufficient memory otherwise it
returns the address of the first byte of the allocated space.

Value of ‘n’ is read from the user ,which is the number of memory locations to be
allocated using malloc().The pointer variable buffer contains the address of the first
byte of the allocated space.It contains NULL where there is insufficient space on the
heap.Number of the bytes allocated or pointed by the pointer buffer can be calculated
using _msize() function which is defined in the library <stdlib.h>.

Data “data” is copied to the location which is pointed by the pointer buffer.

Memory for the pointer buffer is reallocated using realloc().The address of the
previously allocated space and the new size 15 is passed to it.Now the size of the
allocated space is changed from 10 to 15. Data “structure” is copied to the reallocated
space.Pointer buffer contains the new data structure.

6. Differentiate between malloc() and calloc() ( 05 marks)

malloc() calloc()
It allocates only single block of requested It allocates multiple block of requested
memory memory
malloc() does not initializes the allocated calloc() initializes the allocated memory
memory to zero. It contains garbage to zero.
value.
Malloc is faster than the calloc Calloc takes little longer than malloc
because of the extra step of initializing the
allocated memory by zero.However, in
practice the difference in speed is very
tiny and not recognizable.
void * malloc(n).Allocates n bytes of void *calloc(n,sizeof(type));
memiory .If the allocation succeeds ,a Allocates a continuous block of memory
void pointer is to the allocated memory is large enough to hold n elements of size
returned. Otherwise NULL is returned. bytes each.The allocated region is
The pointer contains the address of the initialized to zero. The pointer contains
first byte of the allocated space. the address of the first block of the
allocated space.
Example: Example:
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int *a,*p,n; int *a,*p,n;
printf(“Enter n\n”); printf(“Enter n\n”);
scanf(“%d”,&n); scanf(“%d”,&n);
p=(int*)malloc(n*sizeof(int)); p=(int*)calloc(n,sizeof(int));

printf(“enter the elements into an printf(“enter the elements into an


array\n”); array\n”);

for(a=p;a<(p+n);a++) for(a=p;a<(p+n);a++)

scanf(“%d”,a); scanf(“%d”,a);

printf(“Elements of array are:\n”); printf(“Elements of array are:\n”);

for(a=p;a<(p+n);a++) for(a=p;a<(p+n);a++)

printf(“%d\n”,a); printf(“%d\n”,a);

} }

Malloc() can one parameter or two. Calloc() always takes two parameters

7. How are static memory and dynamic memory allocations different?Write a


program to sort 10 numbers using malloc() . (10
marks)

Static memory allocation Dynamic memory allocation


Memory is allocated during compile time Memory is allocated during execution
time.
Faster execution than dynamic Slower execution than static
More memory space is required Less memory space is required
Variables remain permanently allocated Allocated only when program unit is
active.
Allocated memory cannot be released Allocated memory can be released using
free()
Allocated size cannot be changed during Memory allocation changes during
execution execution of the program depending upon
the number of input or elements.
There may be wasting of memory or Memory can be expanded using realloc ()
insufficient memory and can be freed using free().
Memory is allocated by declaring a Memory is allocated using memory
variable allocation functions.
Example: array Example: linked list

Program to sort 10 numbers using malloc.

#include<stdio.h>

#include<stdlib.h>

void main()

int n,*p,i,j,temp;

printf(“Enter the number of elements\n”);

scanf(“%d”,&n);

p=(int *)malloc(n*sizeof(int));

if(fp==NULL)

printf(“memory allocation unsuccessful\n”);

exit(0);

printf(“enter the elements one by one\n”);

for(a=p;a<p+n;a++)
scanf(“%d”,a);

for(i=0;i<a+n;i++)

for(j=0;i<n;j++)

if(*(p+i)<*(p+j))

temp=*(p+i);

*(p+i)=*(p+j);

*(p+j)=temp;

printf(“The sorted array using malloc is:\n”);

for (a=p;a<p+n;a++)

printf(“%d\n”,*a)’

OUTPUT:

Enter the value of n

Enter the elements one by one

14

16

4
The sorted array using malloc is :

14

16

Write a program to illustrate memory allocation using malloc() function.

A block of memory can be allocated using the function malloc().The malloc function
reserves a block of memory specified size and returns a pointer of the type void.It can
be converted to any of the type by specifying as cast-type.

Example:

float *avg;

avg=(float*)malloc(n*sizeof(float));

The above example allocates the memory for the variable avg of type float.The
allocated memory is equal to the n times the size of float and the address of the first
byte of the memory is assigned the pointer avg of type float.

#include<stdio.h>

#include<stdlib.h>

void main()

int *ptr,sum=0,*a;

int n;

printf(“Enter how many elements you want to store\n”);

scanf(“%d”,&n);

ptr=(int*)malloc(n*sizeof(int));/*allocates memory dynamically the allocated memory


is n times the size of an integer.*/

if(ptr==NULL) //Allocation fails due to insufficient space in heap


{

printf(“\n Error in allocating memory\n”);

exit(0);

printf(“Enter the elements one by one\n”);

for(a=ptr;a<ptr+n;a++)//reading elements into an array

scanf(“%d”,a);

printf(“Elements of array are\n”);

for(a=ptr;a<ptr+n;a++)//Displays elements of an array

printf(“%d”,*a);

for(a=ptr;a<ptr+n;a++)//Finding sum of all the elemnts

sum=sum+a;

printf(“sum=%d”,sum);//Display the sum of all the elements

OUTPUT:

Enter the number of elements you want to store

Enter the elements one by one

10

20
30

40

50

Elements of array are:

10

20

30

40

50

Sum=150

The above illustrates the sum of n numbers in an array. Here the memory allocation is
done using malloc (). The allocated memory is equal to the n times the size of an
integer.

If the memory allocation fails due to the insufficient space in heap ,malloc () function
returns NULL otherwise the variable ptr contains the address of the first byte of the
allocated memory.

The values are read one by to the location which is pointed by ptr .The value of ptr is
assigned to another pointer variable ‘a’ .Values are read from into the address of the
first location till (p+n-1)th location’s address .Each time the value of the pointer is
incremented by scalar factor. Value pointed by the pointer ‘ptr’ is made to pointed by
the pointer ‘a’. These values are added till (p+n-1)th location. Finally the value of sum
is displayed.

8. Write a program to illustrate memory allocation using calloc() function.( 10


marks)

/* To find factorial of individual elements in an array*/

#include<stdio.h>

#include<stdlib.h>

void main()

{
int *p,*a;

int fact,n,m;

printf(“Enter the number of elements into an array\n”);

scanf(“%d”,&n);

p=(int*)calloc(n,sizeof(int));

if(p==NULL)

printf(“Insufficient memory\n”);

exit(0);

printf(“Enter the elements one by one\n”);

for(a=p;a<p+n;a++)

scanf(“%d”,a);

printf(“Elements of array are:\n”);

for(a=p;a<p+n;a++)

printf(“%d\n”,*a);

for(a=p;a<p+n;a++)

fact=1;

for(m=1;m<=*a;m++)

fact=fact*m;

printf(“factorial of %d is %d\n”,*a,fact);

OUTPUT:
Enter the number of elements into an array

Enter the array elements one by one

Elements of array are:

Factorial of 4 is 24

Factorial of 2 is 4

Factorial of 3 is 6

The above example illustrates the use of calloc() for dynamic memory alloacation.

The value is ‘n’ is received from the user which is the number blocks you want to
allocate. Total ‘n’ blocks of memory is allocated each of two bytes. On success the
address of the first region or block is stored in the pointer variable p otherwise it
returns NULL. The value at p is assigned to the pointer variable a. The address stored
in the pointer p is assigned to a. The values are read into the starting address till (p+n-
1)th address into the location using pointer variable a. Each time the value of ‘a’ is
increment by the scalar factor*1.

The each value from the blocks are accessed through the pointer ‘a’ when we access
new block the variable fact is set to 1.Factorial of each elements from the block are
calculated using fact=fact*m. Factorial loop is initialized to the starting value 1 till it
reaches the value pointed by the pointer a. Finally the value of fact is displayed. This
process continues till we access the value of (p+n-1)th block.

9.Write a program to illustrate reallocation of memory using reallocate ()


function.

#include<stdio.h>

#include<stdlib.h>
void main()

int *p,*a;

int i,n;

chat ch;

printf(“how many elements you want to store?\n”);

scanf(“%d”,&n);

p=(int *)calloc(n,sizeof(int));

printf(“Enter the array elements\n”);

for(a=p;a<p+n;a++)

scanf(“%d”,a);

printf(“Do you want to change the size of an array\n”);

scanf(“%c”,&ch);

if(ch==’y’)

printf(“enter the new size of n\n”);

scanf(“%d”,&n);

p=(int*)realloc(p,n);

printf(“Enter the array elements\n”);

for(a=p;a<p+n;a++)

scanf(“%d”,a);

for(a=p;a<p+n;a++)

sum=sum+*a;

printf(“%d\n”,sum);

}
OUTPUT:

how many elements you want to store?

Enter the elements one by one

Do you want to change the size

Enter the new size

Enter the elements one by one

Elements of array are:

Sum=21
The above example illustrates the use of realloc() for changing the allocated memory
using calloc() or malloc().The number of memory locations for storing array elements
is allocated using calloc().Total ‘n’ locations are allocated each of the size 2 bytes.

The pointer variable ‘p’ has the address of the first memory space which is allocated
using calloc().Elemnts to the allocated space are entered starting from the first space
address till (p+n-1)th address.

If the user don’t want to alter the memory then the character ’n’ is entered otherwise
the character ‘y’ is pressed .User enters new size to reallocate and the address of the
first byte which is allocated busing calloc().New elements are entered. Sum of all the
elements from the address of the first byte till (p+n-1) byte are calculated.

10.List and explain the memory allocation functions in C

In C memory can be allocated by using three functions they are:

i)malloc():Allocates requested size of bytes and returns a void pointer pointing to the
first byte of allocated space.

ii)calloc():Allocates the space for an array element’s, initializes them to zero and then
returns a void pointer to the memory.

iii)realloc():Modify the size of previously allocated space.

i) Malloc():
 A block of memory can be allocated using the function malloc.
 The malloc() function reserves a block of memory of specified size and returns
a pointer of type void. This means that we can assign it to any type of pointer.
 malloc() does not initialize the memory allocated during the execution. It
carries garbage value
Syntax:

pointer variable=(cast-type*)malloc(byte-size);

Pointer variable is of a type cast- type. The malloc returns a pointer to an area of
memory with size byte-size.

Example:

x=(int)malloc(100*sizeof(int));

The above example allocates 100 times the size of an integer bytes is reserved and the
address of the first byte of the memory allocated is assigned to the pointer of x of type
int.

Similarly, the statement


cptr=(char*)malloc(10);

allocates 10 bytes of space for the cptr of the type char.

We can also use malloc() to allocate space for complex data types such as structures.

Example: st_var=(struct store*)malloc(size of(struct store));

Where st_var is a pointer of type struct store.

ii)Calloc():

calloc() is used for requesting memory space at run time for storing derived data types
such as arrays and structures. While malloc() allocates a single block of memory of
storage space , calloc allocates multiple blocks of storage, each of the same size and
then sets all bytes to zero.

The general form/ syntax of calloc is:

pointer_variable=(cast-type *)calloc(n,elem-size);

The above statement allocates contiguous space for n blocks, each of size elem-size
bytes. All bytes are initialized to zero.

Parameter:

It takes two parameters one is the value n ,which the number of elements for which
you want to allocate memory and elem-size is the size of each element in bytes.

Return value: On success a pointer to the first byte of the allocated region is
returned. If there is no enough space, a NULL is returned.

Example:

p=(int *)calloc(5,sizeof(int));

In the above example 5 blocks of memory is allocated each of size 2 bytes .Assuming
an integer occupies 2 bytes of memory. It returns void pointer by default it is
converted integer pointer as the type of pointer variable p is integer.

iii)realloc():

At the times memory allocated by using calloc() or malloc() might be insufficient or in


excess. In both the situations we can always use realloc() to change the memory size
already allocated by calloc() and malloc().This process is called reallocation of
memory.
The function realloc() reallocates a memory block with a specified new size.If you call
realloc() the size of the memory block pointed to by the pointer is changed to the
given size in bytes.This way you are able to expand and reduce the amount of memory
you want to use.

It is possible that the function moves the meory block to anew location, in which the
function will return new location.

If the size of the requested block is larger then the previous block then the value of the
new portion is intermediate.

If the pointer is NULL then the function will behave exactly like the function
malloc().It will assign a new block of a size in bytes and will return a pointer to it.If
the size is zero then the memory that was previously allocated is freeds or if a call to
the function free()was given it returns a NULL pointer in that case.

Syntax:

(cast type*)realloc(pointer variable,newsize);

Parameter: This function takes two parameter one is pointer and another one is new
size.

A pointer variable to a previously allocated block of memory.

A new size in bytes for the new memory block.

Return value: Will return a pointer to the reallocated memory block.If the function
fails then a NULL pointer is returned.

Example:

(int *)realloc(ptr,30);

Using realloc we are changing the size of the memory .ptr is a pointer variable which
is pointing to the previously allocated memory using malloc() or calloc().The size of
the allocated block is changed to 30 which is a new size for the memory after realloc.

Example program:

#include<stdio.h>

void main()

char ch;
int *p,*a;

int n;

printf(“enter your choice\n”);

scanf(“%c”,&ch);

switch(ch)

case ‘m’:

printf(“memory allocation using malloc\n”);

p=(int*)malloc(n*sizeof(int));

printf(“enter the elements into an array\n”);

for(a=p;a<(p+n);a++)

scanf(“%d”,a);

printf(“Elements of array are:\n”);

for(a=p;a<(p+n);a++)

printf(“%d\n”,a);

break;

case ‘c’:

printf(“memory allocation using calloc\n”);

p=(int*)calloc(n,sizeof(int));

printf(“enter the elements into an array\n”);

for(a=p;a<(p+n);a++)

scanf(“%d”,a);

printf(“Elements of array are:\n”);

for(a=p;a<(p+n);a++)

printf(“%d\n”,a);

break;
case ‘r’:

printf(“memory allocation using calloc\n”);

p=(int*)calloc(n,sizeof(int));

printf(“enter the elements into an array\n”);

for(a=p;a<(p+n);a++)

scanf(“%d”,a);

printf(“Do you want to reallocate memory?\n”);

scanf(“%c”,&ch);

if(ch==’y’)

Printf(“Enter the new size\n”0;

Scanf(“%d”,&n);

p=(int*)realloc(p,n);

printf(“enter the elements into an array\n”);

for(a=p;a<(p+n);a++)

scanf(“%d”,a);

printf(“Elements of array are:\n”);

for(a=p;a<(p+n);a++)

printf(“%d\n”,a);

break;

default:printf(“Invalid choice\n”);

break;

Question bank
5 marks questions

1. Define dynamic programming in C and its advantages.

2. Give the differences between malloc() and calloc().

3. Explain how to allocate single block of memory in C with an example.

4. With an example explain how to alter the size of previously allocated space.

5. Explain how to allocate multiple block of memory with an example.

6. Explain free. What are its advantages?

10 marks questions

1. Explain dynamic memory allocation in C using memory map.

2. List and explain Dynamic memory allocation functions in C.

3. Write a program to illustrate memory allocation using malloc().

4. Write a program to illustrate memory allocation using calloc().

5. Write a program to illustrate reallocation of memory using realloc().

6. How are static and dynamic memory allocations different? Write a program to
sort 10 numbers using malloc().

You might also like