The ‘C’ programming language supports Dynamic memory allocation in which the programmer can allocate and de-allocate memory whenever required. Dynamic memory allocation means memory allocation and deallocation at runtime, as and when required.
Allocating a block of memory using malloc() function
The malloc() function allocates the specified number of bytes and returns the address of the first byte of the block. It returns NULL if allocation is unsuccessful or if num is 0. Explicit type casting is required because by
default, malloc returns a void pointer.
Syntax: pointer =(datatype*)malloc(number_of_bytes); Example:
int *ptr; /* pointer to the block*/
ptr=(int *)malloc(n *sizeof(int));
Allocating a block of memory using calloc() function
It allocates a group of objects and initializes the bytes to 0.
Syntax: void *calloc(int num, int size);
Here num is the number of objects to allocate and size is the size (in bytes) of each object.
Example:
int *ptr;
ptr=(int *)calloc(n, sizeof(int));
Resizing memory using realloc() function
It changes the size of a block of memory that was previously allocated with malloc() or calloc().
Syntax: void * realloc(void *ptr, int size);
Example:
int *ptr;
ptr=(int*)malloc(10*sizeof(int)); //allocate memory for 10 integers ptr=(int *)realloc(ptr,20*sizeof(int)); //resize the memory block to 20 integers
Freeing or de-allocating memory using free() function
Syntax: void free(void *ptr);
C Program illustrate dynamic allocation and de-allocation of memory for 1D array
#include<stdio.h>
#include<stdlib.h>
main()
{
int *ptr, n, i,sum=0;
printf("\n How many elements ?:");
scanf("%d", &n);
ptr=(int *)malloc(n*sizeof(int)); /* allocate memory*/
if(ptr==NULL)
{ printf("\n memory not allocated ");
exit(0);
}
printf("\n Enter the element :\n");
for(i=0; i<n; i++)
{ scanf("%d", ptr +i);
sum = sum + *(ptr +i);
}
printf("\n You entered :\n");
for(i=0; i<n; i++)
printf("%d\n", ptr[i]); //or *(ptr+i)
printf("\nThe sum =%d",sum);
free(ptr); /* Free allocated memory */
}
Also Read
- Static and Dynamic Memory Allocation
- Memory Leak and Dangling Pointer
- Memory Allocation for 2D Array
- Pointer constant and constant pointer
- Some Pointer Declaration and their Meanings
- Function and pointers
- Initializing Pointer to Pointer
- Pointer to Pointer Multiple Indirection
- Relationship between Arrays and Pointers
- Pointer to Array
- Pointer Arithmetic
- Types of Pointers
- Illustrate Basic Pointer Use
- Using Pointer
- Intializing Pointer
- Declaring Pointer
- Application of Pointers
- Value Model VS Reference Model
- What is Pointer
Comments
Post a Comment
Please give us feedback through comments