×

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

Decimal to Binary in C

What is a decimal number? A decimal number is a number represented in the decimal number system. This system of binary conversion uses base 10 to represent numbers, i.e. the digits...

3 minutes read.

Pure Virtual Function in C

Before knowing about the pure virtual function some of the important points about the virtual function in C++ are given below. In c++ the member function that is defined in the...

4 minutes read.

Sizeof in C

A pointer in C is defined as a variable that stores the information of the address of another variable. A pointer can be incremented or decremented, which means we can...

4 minutes read.

C Program to find the size of a File

Before knowing about the Program, you need to understand what the size of a file is. After that, you should know how it is going to work with the given...

4 minutes read.

Call Back Function in Embedded C

Callback function are one the most remarkable systems in C. A callback function is any code that is passed as a contention to another code, so this is the last...

3 minutes read.

Find median of 1D array using function in C

Introduction: Here, we discuss how we can find the median of a 1D array using a function in C. The median is the value in the middle of the sorted...

3 minutes read.

Why C is a middle level language

The C programming language is generally referred to as a high level language but we glance through the backend of C, i.e the working of C as a programming language...

4 minutes read.

7 Best IDEs for C/C++ Developers in 2024

As we all know that in programming languages, C is known as the building block which cannot be contradicted, and C++ is the prolong kind of C and it can...

4 minutes read.

Difference between Array and List in C

C# Array vs List is where the abstraction and implementation of human computing meet.  Arrays are incredibly related to the hardware concept of contiguous and contiguous memory, where each part is...

3 minutes read.

Quick sort in C

Quick-sort, in the same way, like a merge sort, follows the principle of the divide and conquer algorithm. It then picks an element as pivot and partitions, and the given...

4 minutes read.

Difference between rand() and srand() function in C

What is the rand()?The rand() means random function. This function is used in C. It generates random numbers in the range of 0 to the RAND_MAX. Suppose we generate a...

3 minutes read.

Banker’s Algorithm in C

Introduction Before doing a "s-state" check to look for potential activities and deciding if allocation should be allowed to continue, the banker's algorithm, a resource allocation and deadlock avoidance algorithm, tests...

5 minutes read.

Queue implementation in C

In the C programming language, the queue is the abstract concept that is similar to stacks. However, it is the part of the data structures that work opposite to that...

4 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.

Two-Dimensional array in C

What is an Array? The collection of a fixed number of elements of homogeneous data types that are stored in contiguous locations in the memory is known as an array. Only...

6 minutes read.

Bank Account System in C using File Handling

This tells about the creation of bank account system using the C language and handling of files in C. Approach Let us see the approaches and the functions how they are covering...

5 minutes read.

Example of Iteration in C

The iterations in the C language are the statements which are executed number of times until a certain condition is reached. These iterations are regarded as “Loops” in C language....

3 minutes read.

Nested Loops in C Programming Examples

A nested loop is generally used when we want to run a loop statement inside another loop statement. This kind of loop is also known as a “loop inside the...

6 minutes read.

CRC Program in C

CRC (Cyclic Redundancy Check) is an error-detection algorithm that is used to detect any errors that may have occurred during the transmission or storage of data. The basic idea behind...

4 minutes read.

Bit Stuffing Program in C

What is a Bit Stuffing? The process of inserting one or more extra bits (0) into data is known as bit stuffing. To provide signalling information to a recipient, these are...

3 minutes read.