Chapter 12
Chapter 12
malloc()
calloc()
alloc.h
realloc()
free()
NINT
Example 1:
ptr=(int*)malloc(10);
Example 2 :
char (*a)[20];
A=(char*) malloc(10*20*sizeof(char));
Note :
free(pointer_variable);
Example 1:
ptr=(int*)malloc(10);
free(ptr);
/* malloc() Function Example */ NINT
#include<stdio.h>
#include<alloc.h>
#include<process.h>
void main()
{
char *str;
if((str=(char *)malloc(10))==NULL){
printf("Not enough memory to allocate buffer\n");
exit(1);}
strcpy(str,"Helloworld");
printf("String is %s\n",str);
free(str);
}
String is HelloWorld
malloc() Example 2
NINT
#include<stdio.h>
#include<conio.h>
void main()
{
int *ptr; //static memory allocation
clrscr();
ptr=(int *) malloc(sizeof(int));
*ptr=100;
printf("\n%u\n",ptr); //address of ptr
printf("\n%d\n",*ptr);
free(ptr);
getch();
}
*sptr=400; startptr=NULL;
sptr++; }
*sptr=300;
sptr++;
Allocating Memory NINT
*ptr=200;
ptr++;
printf("\n ptr 3= %d\n",*ptr);
NINT
Example 1:
ptr=(int*)calloc(5,10);
On execution of this function 5 memory blocks of size 10 bytes
are allocated and the starting address of the first byte is assigned to the
pointer ptr of type int
/* Calloc() Function example */ NINT
#include<stdio.h>
#include<string.h>
#include<alloc.h>
void main()
{
char *str=NULL;
str=(char *)calloc(20,sizeof(char));
strcpy(str,"Welcome to world");
printf("String is %s\n",str);
free(str);
}
Example 1:
y=(int*)malloc(50)
ptr=(int*)realloc(y,30);
//REALLOC() FUNCTION EXAMPLE
#include<stdio.h> NINT
#include<string.h>
#include<alloc.h>
void main()
{
char *str;
str=(char *)malloc(5);
strcpy(str,"Kalai");
printf("String is %s\n Address is %u\n",str,str);
str=(char *)realloc(str,5);
strcpy(str,"Sangeetha");
printf("String is %s\n New Address is %u\n",str,str);
free(str);
}
Like all variables a pointer must be declared before they are used
The indirection (or) the deferencing operator is used to access the value of an address
in a pointer
The three values that can be used to initialize a pointer are zero, null and address
A pointer that has not been initialized is referred to as the dangling pointer
Arrays are automatically passed by reference since the value of the array name is the
address of the array
Call by reference is the process of calling a function using pointers to pass the
address as argument must include a pointer as its parameter.
NINT
EXERCISES