Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
ANDHRA PRADESH
Name : Murali Krishna Chintala
Designation : Lecturer in CME
Branch : Computer Engineering
Institute : SUVR & SR GPW, Ethamukkala
Year/Semester : III Semester
Subject : UNIX & C
Subject Code : CM – 304
Topic : Basics of pointers
Duration : 50 Min
Sub Topic : Dynamic memory management functions
Teaching Aids : PPT, Animations
CM304.75 1
Objective
malloc()
calloc()
free()
realloc()
CM304.75 2
Recap
In the previous class, we discussed about
CM304.75 3
Dynamic Memory Allocation
CM304.75 6
malloc() function
Example:
ptr=(int *) malloc(10);
CM304.75 7
malloc () function
Example:
ptr= (int *) malloc (10*size of(int));
CM304.75 8
malloc () function
CM304.75 9
Example program using malloc() to enter 10
numbers and print them
#include<stdio.h>
main()
{
int i,*ptr;
ptr=(int *)malloc(10*sizeof(int));
for(i=0;i<10;i++)
{
printf(“number %d”,i+1);
scanf(“%d”, (ptr+i);
}
CM304.75 10
Example program using malloc() to enter 10
numbers and print them
Contd..
for(i=0;i<10;i++)
printf(“%d\n”, *(ptr+i);
} /* end of main */
CM304.75 11
calloc() function
CM304.75 12
calloc() function
Syntax:
ptr=(data-type *) calloc(n,size);
CM304.75 13
calloc() function
Example:
ptr=(int *) calloc(5,2);
CM304.75 14
free() function
This is used to free (release or de allocate) the
block of unused or already used memory.
Syntax:
free(ptr);
CM304.75 15
free() function
Example:
ptr= (int *)malloc((10);
free(ptr);
The first statement allocates memory space of
10 bytes and returns the starting address to
pointer variable ptr.
CM304.75 16
realloc() function
CM304.75 17
realloc() function
Syntax:
new-ptr= realloc(old-ptr,new-size);
CM304.75 18
realloc() function
Example:
y=(int *) malloc(10);
x=realloc(y,30);
CM304.75 21
Quiz
CM304.75 22
Quiz
b) null
CM304.75 23
Quiz
b) null
CM304.75 24
Assignment
CM304.75 25
Frequently Asked Questions
CM304.75 26