C Programming

Difference between malloc and realloc in C Programming

The malloc() and the realloc(); both functions are used for the dynamic memory allocation and in this write-up, we will discuss the comparison of both; realloc() and malloc() functions in detail. But before understanding these functions, let us discuss the difference between static and dynamic memory in C programming.

In C programming, when we run a program, it occupies some memory on the system. If we use the static memory, we have to assign a fixed memory block from the system, then after the execution of the program, two scenarios can happen; the program will either need a larger block size than the size declared or it will need the smaller size block of memory. If the memory block becomes less for the executed program, the results will be not precise and if the block size is larger for the executed program then the remaining free memory of the block is of no use.

To avoid this, it is preferred to use dynamic memory in c programming which has different types of functions.

What is a malloc() function in C programming

In C programming, if we use static memory then we cannot change the memory size during the execution of the program. It is a recommended practice to use dynamic memory in C programming so memory size can be altered during the execution of the program.

For the use of dynamic memory, we have to include a header file “stdlib.h”, which includes all the functions of dynamic memory. The malloc() is also a member of stdlib.h library and is used to assign memory to the executed program. When a malloc() function is called in a program, it sends a request to the heap of the system, which either assigns the requested memory block to the malloc() function or will return a null value if there is not sufficient space on the heap.

The malloc() requests the memory block according to the need of the executed program and when the program is executed successfully, we can return back the memory block to the heap by using the free() function, so it can be used for the execution of other instructions.

The general syntax of the malloc() function is:

ptr_name = (cast-type*) malloc(size);

The explanation to the above syntax is simple:

  • We can use any name for the pointer(pointer are used to store addresses)
  • Then we have to declare the data type or cast type for the pointer like int and char
  • And finally using the malloc() function and inside the function, we have to mention the size of memory needed

For a better understanding, we will consider an example, create a file with the name of mal_txt.c and type the following script:

#include <stdio.h>

#include <stdlib.h>

int main() {
   int a = 4, i, *ptr, s = 0;
ptr = (int*) malloc(a * sizeof(int));
if(ptr == NULL) {
printf("\nError! memory not allocated.");
exit(0);
   }
printf("\nEnter elements of array : ");
for(i = 0; i< a; ++i) {
scanf("%d", ptr + i);
      s += *(ptr + i);
   }
printf("\nSum : %d", s);
printf(“\n”);
   return 0;
}

To compile the mal_txt.c file, we use the gcc compiler:

$ gcc mal_txt.c -o mal_txt

Once the file is compiled successfully without any error, execute the code using the command:

$ ./mal_txt

In the above code, we are creating the array and printing the sum of the elements of the array. A detailed explanation of the above program is:

  • We have included the two libraries; stdlib.h for the use of dynamic memory functions and stdio.h for the input and output functions
  • We declared four variables a,s, i, and *p where “*” is used with “p” because it’s a pointer and store the location instead of variables
  • We employed the malloc() function and used the size of a variable “a”, which means it will request the memory from the heap according to the size of “a” and the pointer “p” will go to the start of the memory allocated
  • Then we used the “if statement”, if the heap has not had sufficient memory, it will return the null value, in this case simply display the “Error! memory not allocated.” using the printf() function
  • If memory is assigned, then with the help of scanf() function it will take four elements from the user, calculate its sum and save it in “s”
  • Finally, will display the value of “s” which is the sum of all the elements of the array

What is a realloc() function in the C programming

Another function of dynamic memory is the realloc() function, it is used to modify the memory block assigned to the malloc() function. The malloc() function as discussed above requests a memory block from the heap, but to modify the size of the memory block so we used the realloc() function instead of deleting the entire memory block and redeclaring the new memory block manually.

The realloc() function is the short form of “reallocation of the memory” and it is used to resize the memory block size assigned by the heap to malloc() or calloc() function. It does not disturb the original contents of the memory block and requests the new memory block from the heap and copies all the data from the old memory block to the new memory block without disturbing any contents of it.

The general syntax of using the realloc() function is:

$ ptr = realloc (ptr,newsize);

The explanation of the above syntax is:

  • Use the pointer variable that is used with the malloc() function
  • Use the realloc() function with the parameters; pointer name and new size you want to assign it

Again we will create a file, real_file.c, and write the code in it for a better understanding of the use of realloc() function:

#include <stdio.h>

#include <stdlib.h>

    int main() {
        int *ptr;
ptr = malloc(200);
        if (ptr == NULL) {
printf("The memory is not allocated.");
exit(0);
        }    
ptr = realloc(ptr,400);
if(ptr!= NULL)
printf("Memory has successfully allocated\n");        
    return 0;
    }

Now compile the real_file.c using the gcc compiler:

$ gcc real_file.c -o real_file

If the file is compiled successfully, run the program using the command:

$ ./real_file

The explanation of the above script is:

  • We included two header files; stdlib.h for the dynamic memory functions and stdio.h for the input and output functions
  • Declared pointer variable *ptr
  • Used the malloc() function and requested the heap to assign 200 bytes, if the memory is not assigned by the heap, “The memory is not allocated.” will be displayed using the printf() function
  • If the memory is assigned, then it will come to the realloc() function and resize the memory from 100 bytes to 400 bytes
  • If the heap assigned it 500-byte memory; it will display the (“Memory has successfully created”)

Conclusion

In C programming, dynamic memory allocation is the manual allocation of memory according to the program requirement. The malloc() and realloc() functions are part of dynamic memory; malloc() is used for the memory allocation and realloc() is used for the reallocation of the memory. In this write-up, we have explained both; malloc() and realloc() functions, how they work, and what is the general syntax of using both of them. Finally, for a better understanding, we executed the examples of both functions.

About the author

Hammad Zahid

I'm an Engineering graduate and my passion for IT has brought me to Linux. Now here I'm learning and sharing my knowledge with the world.