Showing posts with label malloc and calloc. Show all posts
Showing posts with label malloc and calloc. Show all posts

Saturday, May 16, 2020

, , , ,

Learn malloc(), calloc(), free() and realloc() function in c



This chapter will help you to learn about Dynamic memory allocation in your c program with the help of using standard library function : - malloc(), calloc(), free() and realloc().

Learn malloc(), calloc(), free() and realloc() function in c
Learn malloc(), calloc(), free() and realloc() function in c


As we know array is a collection of elements once the size of array is declared, It cannot be changed.

So Sometimes declared size is insufficient for an array. To solve these problems we can use Dynamic memory allocation During run time in c programming. This process is known as dynamic memory allocation in C programming.

To allocate memory dynamically in c programming, library funcation malloc(), calloc(), free() and realloc(), are used These functions are defined in the <stdlib.h> in C programming
header file. 

Let's learn about these function in c programming : - 


Malloc () Function In C  : -

The malloc() function stands for memory allocation in c programming. malloc() function is used to allocate block of memory dynamically.It reserves memory space of specified size and returns the null pointer pointing to the memory location. that pointer is usually a type of viod. so previous line clears that wen can assign malloc() function to any pointer.

Syntax for malloc() : -


ptr = (cast_type *) malloc (byte_size);

  • ptr is a pointer of cast_type.
  • The malloc function returns a pointer to the allocated memory of byte_size.

Example: ptr = (int *) malloc (50)

When this program statement is executed then a memory space of 50 byte is reserved, and address of the fist byte of reserved space is assign to pointer ptr of int type.

Example of malloc() function

#include 
int main(){
int *ptr;
ptr = malloc(15 * sizeof(*ptr)); /* a block of 15 integers */
    if (ptr != NULL) {
      *(ptr + 5) = 480; /* assign 480 to sixth integer */
      printf("6th integer is %d",*(ptr + 5));
    }
}

Output

6th integer is 480


malloc() function can be used With the character data type as well as complex data types such as structures.

free() Function : -  


As we know memory for variables is automatically deallocation at compile time in C programming But in dynamic memory allocation we have to deallocate memory with the help of "free() function. If dealocation is not done then  you may encounter out of memory error".

The free() function in c programming is basiclly called for release/deallocate memory. By freeing the memory in our program then we have more memory to use.

Example For  free() Function : -  

#include 
int main() {
int* ptr = malloc(10 * sizeof(*ptr));
if (ptr != NULL){
  *(ptr + 2) = 50;
  printf(" 2nd integer is %d",*(ptr + 2));
}
free(ptr);
} 

Output : -

2nd integer is 50

calloc() Function in C programming: - 


The calloc() function stands for contiguous allocation in c programming. calloc() function is used to allocate multiple number of block of memory dynamically.

calloc function is the same as malloc() function but it allocates the multiple numbers of the block of memory dynamically and each block allocated by calloc() function is the same size.

Syntax : -

ptr = (cast_type *) calloc (n, size);


  • Above statement is used to allocate n memory block of same size.

  • After the memory space is allocated, then all the bytes are initialized to zero.

  • The pointer which is currently at the first byte of the allocated memory space is returned. 
When a error is occured like shortage of memorythen a null pointer is returned 

calloc() Example  : - 

#include 
    int main() {
        int i, * ptr, sum = 0;
        ptr = calloc(10, sizeof(int));
        if (ptr == NULL) {
            printf("Error! memory not allocated.");
            exit(0);
        }
        printf("sum of the first 10 terms \ n ");
        for (i = 0; i < 10; ++i) { * (ptr + i) = i;
            sum += * (ptr + i);
        }
        printf("Sum = %d", sum);
        free(ptr);
        return 0;
    }

OUTPUT : -

sum of the first 10 terms sum = 45

realloc() Function in C programming: - 


realloc() stands for reallocation of memory realloc() function is use to add more memory size to already allocated memeory. It gives an opportunity to expand the current block without touch the orignal content.

realloc() function can also be used to reduce the size of  previously allocated memory. 

Syntax : -
ptr = realloc (ptr,newsize);

Above Statement allocates a new memory space with the specified size in the variable new. After executing the function pointer will returned to the first byte of memory block which can be samller and larger then previous assigned memory block, and we can't be sure that the newly allocated block will point to the same location as that of the previous memory block. realloc() function also copy all the data in the new one and make sure that data will remain safe.

Example for realloc() : -  



#include 
int main () {
   char *ptr;
   ptr = (char *) malloc(10);
   strcpy(ptr, "Programming");
   printf(" %s,  Address = %u\n", ptr, ptr);

   ptr = (char *) realloc(ptr, 20); //ptr is reallocated with new size
   strcat(ptr, " In 'C'");
   printf(" %s,  Address = %u\n", ptr, ptr);
   free(ptr);
   return 0;
} 

If any error occur then it returns a null pointer,  and free the previous data is alsoed freed.

malloc(), calloc(), free() and realloc() functions is used to help all dynamic memory allocations and it will help yo save the memory in c programming programs.