×

Malloc function in C

When the user or programmer does not know how much memory space is needed in the application, it a needs dynamic memory allocation during runtime.

Dynamic memory allocation helps us to use memory efficiently by enabling us to allocate Memory continuously during runtime rather than in advance. This makes us use the memory space effectively and helps us stay in Memory.

The predefined library function known as Malloc standsfor memory allocation.

When a program runs, Malloc is used to allocate a memory block of a specific size.

The characteristics of the Malloc () function allow us to allocate Memory at some point during runtime. These characteristics are defined inside the header.

The characteristic requires a length in bytes as input and, upon successful memory allocation, provides a void pointer that may be cast to any other kind.

The C malloc() function provides a void type pointer, allowing us to assign dynamic Memory for any data type (primitive or user-defined). A NULL pointer will be returned if the minimum amount of memory space is not available.

Syntax of Malloc () Function in C

ptr = ( cast_ type *) malloc (byte_size);  

Return Value of Malloc () Function in C

The C language's Malloc function only allocates one memory block at a time, and the assigned memory address carries the initial garbage cost.

A void pointer corresponding to the Memory allocated by the C malloc function is the return value or type of the Malloc () function in C. The advantage of using a void pointer as the return type is that it allows us to do this for any data type pointer.

Parameters of Malloc() function

The number of bytes of Memory that will be allocated is the sole argument required by the C language's Malloc function. Because the size of each data type might vary depending on the compiler, the sizeof() method is typically used to determine how many bytes are needed.

Free():-

The Memory allotted during runtime does not automatically release itself. Memory allocated at runtime can be manually released using the free() function.

The same header has a description for the free() function. The attribute accepts a pointer and releases the Memory that is pointing to the reference.

Dynamic Memory, often known as heap memory, is the Memory that is allocated to variables when the C programming language's malloc() or calloc() operations are used.

When a programmer defines a variable for a primitive or user-defined data type, static Memory or stack memory is allotted to it.

A program to check if memory is created using the Malloc () function.

#include <stdio.h>  
#include <stdlib.h>  
int main ()  
{  
    // declare a pointer of type int //
    int *pt; 
    // use the Malloc () function to define the size of the block in bytes  
    pt = malloc (sizeof(int));  
      
    // use if the condition that defines ptr is not equal to null  
    if (pt != NULL)  
    {  
        printf ( " Memory is created using the malloc() function ");  
    }  
    else  
    {
    printf ( " memory is not created ");
    }
    return 0;     
}   

OUTPUT

Malloc function in C

Program to create a dynamic memory using the Malloc () function

#include <stdio.h>  
#include <stdlib.h>   
int main ()  
{  
    // declare the local variables  //
    int *ptr, size, i;  
      
    printf (" Enter the allocated size of memory ");  
    scanf (" %d", &size);     
    // use the Malloc () function to define the size of the block in bytes // 
    ptr = malloc (size * sizeof(int));    
    // use if the condition that defines ptr is not equal to null //  
    if (ptr != NULL)  
    {  
        // get input from the user and print it  //
        printf (" Enter numbers from the user: ");        
        for ( i = 0; i < size; i++)  
        {  
            scanf (" %d", ptr + i); 
     // stores the numbers from base address of memory  //
        }         
        printf (" Numbers are stores in contiguous memory: \n ");         
        for ( i = 0; i < size; i++)  
        {  
            printf (" \n The number is: %d", *(ptr + i)); 
          // here *(ptr + i) is same as ptr[i]  
        }  
        printf (" \n Memory is created using the malloc() function ");  
        return 0;  
    }  
    else  
    printf (" memory is not created ");  
    return 0;  
}  

OUTPUT

Malloc function in C

free() function program using Malloc()

#include <stdio.h>
#include <stdlib.h> 
int main()
{
   int* ptr; 
   ptr = (int*)malloc(5* sizeof(int)); 
   if (ptr==NULL)
   {
         printf( "Memory not allocated \n"); 
   }
 else 
  {
      printf( "Memory allocated successfully \n ");
      for (int i=0; i<5; i++) 
      {
         ptr[i]=i; 
      }
      printf("The elements of the •array are: "); 
      for (int i=0; i<5; i++) 
      {
         printf("%d \n", ptr[i]); 
      }
  }
 free(ptr);
 return 0; 
}

OUTPUT

Malloc function in C

free() function program using Calloc()

#include <stdio.h>
#include <stdlib.h> 
int main()
{
   int* ptr; 
   int n;
   printf(" Enter the elements you want ");
   scanf("%d",&n);
   ptr = (int*)calloc(n, sizeof(int)); 
   if (ptr==NULL)
   {
         printf( "Memory not allocated \n"); 
   }
 else 
  {
      printf( "Memory allocated successfully \n ");
      printf(" Enter the values ");
      for (int i=0; i<5; i++) 
      {
         scanf("%d" ,&ptr[i]); 
      }
      printf("The elements of the •array are: "); 
      for (int i=0; i<5; i++) 
      {
         printf("%d \n", ptr[i]); 
      }
  }
 free(ptr);
 return 0; 
}

OUTPUT

Malloc function in C

Related Topics

Explain the Increment and Decrement Operators in C

In the C programming language, the increment operator (++) and the decrement operator (--) are used to increase or decreasing a variable’s value by 1, respectively. The increment operator is written...

10 minutes read.

First Fit Program in C

This is one of the easiest ways to allocate memory. The main goal is to divide the memory into several fixed sizes. In C, there is only one process for...

3 minutes read.

FIFO Example in the C Language

FIFO is an acronym that means "First In, First Out." It is a data structure handling method in which the first element is handled first, and the last element is...

3 minutes read.

Sum of digits in C++

Sum of digits in C++ There are various ways to find the sum of the digits of a number in C++. We can use containers like arrays or other simple cases...

4 minutes read.

Fibonacci series program in C using Recursion

In this tutorial, we’ll explore how to utilise recursion to build the Fibonacci sequence in C language. What does the term "Fibonacci Series" mean? The following number in a Fibonacci number series is...

2 minutes read.

Pascal Triangle in C

The pascal triangle in c is an array of binomial coefficients in triangular form. Here the nth row contains the binomial coefficient of ncr.In a pascal triangle, every number is...

2 minutes read.

Bubble sort in C

Bubble sort in C Bubble sort is defined as the algorithm that is used for the sorting mechanism. It follows the technique of replacing the first index with the more minor...

4 minutes read.

strtok() and strtok_r() functions in C with examples

strtok() and strtok_r() functions in C with examples C offer various strtok() and strtok r() methods for a string to be separated by a certain delimiter. Dividing a string is a...

2 minutes read.

Results of Comparison Operations in C and C++

In this tutorial, we will explore comparison operators and how the system should compare an incoming value supplied as a context parameter to a given value or range of values. A...

2 minutes read.

Assert() Function in C

Assert (): In C, the statements are executed with the exit statement. In C language declare, and it tests the condition parameters. If the statement executed will be false, it...

3 minutes read.

fgets() function in C

fgets() function is present in standard input and output library i.e, stdio.h library. It is a built-in function or pre-define function. It is used to read the specified stream from...

4 minutes read.

Type Conversion in the C

The process of changing one data type to another in the C programming language is known as "type conversion." The type conversion method is only executed on data types that...

4 minutes read.

C pre-processor

The C processor is a macro processor which is used to compile the source code of the program (step by step) . It is not a part of the compiler....

4 minutes read.

Tower of Hanoi in C

What is Tower of Hanoi? The Tower of Hanoi is a gaming problem that was created in 1883 by a French mathematician named Édouard Lucas. The Tower of Hanoi temple in...

4 minutes read.

Different ways to Declare the Variable as Constant in C

There are a wide range of ways of making the variable as steady Using const keyword: The const catchphrase permits a software engineer to inform the compiler that a specific variable should...

5 minutes read.

What is the main in C?

In the C programming language, "main" is a predefined term or function. It is the primary function in every C program and is in charge of beginning and terminating the...

6 minutes read.

Control statement in C

What is a control statement? A control statement helps us to control the flow of the program. The control statement helps us to execute the program's instructions in a user-defined order....

8 minutes read.

Character Set in C

Introduction Every language has some basic elements which are used to represent information. The English language includes alphabets which together shape a sentence, after which the sentences are used to shape...

3 minutes read.

fflush in C

In this article, we will understand what is fflush(), the need for fflush and fflush(stdin), and fflush(stdout). The fflush() function is used to clear the output buffer and move the buffered...

3 minutes read.

Comments in C

Comments are used to comment on the line of code in the program. Comments are a way of inserting remarks and reminders into code without affecting its behavior. The compiler...

1 minute read.