Showing posts with label Dynamic memory allocation. Show all posts
Showing posts with label Dynamic memory allocation. Show all posts

What is Malloc() function in C Programming Language?



What is Malloc() function in C Programming Language?

A malloc() function is used for  dynamic memory allocation. It is defined in stdlib.h or malloc.h depending on the operating system. Memory allocation by malloc() is persistent.  
  • void  *malloc(size_t size);


Example:

  • #include<stdio.h>
  • #include<stdlib.h>
  • void main()
  • {
  •           int array[10];
  •           int *ptr = (int *) malloc(10 * sizeof (int));
  • if (ptr == NULL)
  • {
  • }
  •           else
  •          {
  •                   free(ptr);
  •                   ptr=NULL;
  •           }
  • }

What is Calloc() function in C Programming Language?


What is Calloc() function in C Programming Language?


A calloc() function allocates space for an array of elements of a certain size and initializes the memory to zero. 

  • void  *calloc(size_t num, size_t size);
Here num is number of objects to allocate and size is the size of each objects. If the allocation is successful then function returns a Pointer to the first byte and if allocation fails then the function returns NULL. 

Examples:

  • #include<stdio.h>
  • #include<stdlib.h>
  • void main()
  • {
  •           unsigned a;
  •           int *ptr;
  •           printf(“Enter the number to allocate:-”);
  •           scanf("%d", &a);
  •           ptr= (int*) calloc(a, sizeof(int));
  •           if(ptr!=NULL)
  •           {
  •                      puts("Memory allocation successful");
  •            }
  •           else
  •           {
  •                     puts("Memory allocation failed");
  •           }
  •           return(0);
  • }


Output:-
  • Enter the number to allocate:- 200
  • Memory allocation successful
  • Enter the number to allocate:- 111111111111
  • Memory allocation failed