Professional Documents
Culture Documents
WINSEM2023-24_BCSE102L_TH_VL2023240501147_2024-01-24_Reference-Material-II
WINSEM2023-24_BCSE102L_TH_VL2023240501147_2024-01-24_Reference-Material-II
WINSEM2023-24_BCSE102L_TH_VL2023240501147_2024-01-24_Reference-Material-II
malloc()
calloc()
realloc()
free()
malloc() allocates single block of requested memory.
ptr=(cast-type*)malloc(byte-size)
• The “malloc” or “memory allocation” method
in C is used to dynamically allocate a single
large block of memory with the specified size.
• It returns a pointer of type void which can be
cast into a pointer of any form.
• It doesn’t Initialize memory at execution time
so that it has initialized each bytes with the
default garbage value initially.
#include<stdio.h> for(i=0;i<n;++i)
{
#include<stdlib.h>
scanf("%d",ptr+i);
int main(){ sum+=*(ptr+i);
int n,i,*ptr,sum=0; }
printf("Enter number of elements: "); printf("Sum=%d",sum);
scanf("%d",&n); free(ptr);
ptr=(int*)malloc(n*sizeof(int)); return 0;
}
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
Example of malloc() in C
#include <stdio.h>
#include <stdlib.h> // Print the array elements
for (int i = 0; i < n; i++) {
int main() { printf("%d ", arr[i]);
int *arr; }
int n = 5;
// Free the allocated memory
free(arr);
// Allocate memory for an return 0;
//array of integers }
arr = (int *)malloc(n * sizeof(int));
int main()
{
return 0;
}
C free() method
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h> printf("Enter elements: ");
for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
int main() { sum += *(ptr + i);
int n, i, *ptr, sum = 0; }
printf("Enter number of elements: ");
scanf("%d", &n); printf("Sum = %d", sum);
free(ptr);
return 0;
ptr = (int*) calloc(n, sizeof(int));
}
if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int *ptr, *ptr1;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %d\n", n);
else {
return 0;
}