Malloc and free functions in C language

In C, the malloc() and free() functions are used for dynamic memory allocation and deallocation, respectively.

The malloc() function stands for memory allocation and is used to dynamically allocate a block of memory at runtime. It takes the number of bytes to be allocated as an argument and returns a pointer to the first byte of the allocated memory block.

Example of malloc() and free():

#include <stdio.h>
#include <stdlib.h>

int main() {
   int *ptr;
   int n = 5;
   
   // Allocate memory dynamically
   ptr = (int*) malloc(n * sizeof(int));
   
   if (ptr == NULL) {
      printf("Error: memory not allocated\n");
      exit(0);
   }
   
   // Assign values to the memory block
   for (int i = 0; i < n; i++) {
      *(ptr + i) = i;
   }
   
   // Print values in the memory block
   for (int i = 0; i < n; i++) {
      printf("%d ", *(ptr + i));
   }
   
   // Free memory
   free(ptr);
   
   return 0;
}

Output:

0 1 2 3 4

In this example, the malloc() function is used to allocate memory for an integer pointer ptr of size n bytes. The pointer is then checked to ensure that the memory allocation was successful. Values are then assigned to the allocated memory block using pointer arithmetic, and the values are printed to the console. Finally, the free() function is used to deallocate the memory that was allocated using malloc().

It’s important to note that the malloc() function returns a void pointer, which must be cast to the appropriate pointer type. It’s also important to remember to deallocate the memory using free() once it is no longer needed to avoid memory leaks.