How to Dynamically Allocate Memory using malloc() in C?

How to Dynamically Allocate Memory using malloc() in C?

27 May 2024
Advanced
1.24K Views
7 min read
Learn with an interactive course and practical hands-on labs

Free C Programming Online Course With Certificate

malloc() Function in C

malloc() Function in C plays an important part in the process of Dynamic Memory Allocation. It is defined in the <stdlib.h> header file. The function allocates particular size bytes of memory and returns the pointer pointing towards the allocated memory.

In this C Tutorial, we'll learn more about Dynamic Memory Allocation, defining malloc() in C Programming with an Example Program, etc. For more understanding of C Programming, consider enrolling in our C Certification Training.

Read More: Top 50 Mostly Asked C Interview Questions and Answers

What is Dynamic Memory Allocation?

Dynamic Memory Allocation in C is the process that allows the developer to dynamically allocate memory during the runtime. That means the size and allocation of the data can be changed if required during the runtime with the help of the method of Dynamic Memory Allocation. Four kinds of functions help in achieving this:

  1. malloc()
  2. calloc()
  3. realloc()
  4. free()

Let's get to know the malloc() function and its application in detail first.

The malloc() in C Programming

The malloc(), which stands for 'memory allocation', is a function for performing memory allocation by allocating the memory in the form of blocks of sizes that are specified. And then, it returns a pointer of void to the starting of that memory block.

Read More: Pointers in C Programming

malloc() syntax in C:

void* malloc(size_t size);

The 'size' keyword is used to specify what number of bytes are needed to be allocated.

Read More: Beginner's Guide to C Programming

malloc() Function in C library with EXAMPLE

We already know what malloc() function does. Now, we will take a look at how to use malloc() in C Program through the below Example in C Compiler

Example

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

int main() {
    int *ptr;
    int n = 5; // Number of integers to allocate

    // Allocate memory for n integers
    ptr = (int*)malloc(n * sizeof(int));

    // Check if memory allocation is successful
    if (ptr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    // Access and manipulate the allocated memory
    for (int i = 0; i < n; i++) {
        ptr[i] = i * 10;
    }

    // Display the allocated memory contents
    printf("Allocated memory contents:\n");
    for (int i = 0; i < n; i++) {
        printf("%d ", ptr[i]);
    }

    // Free the allocated memory
    free(ptr);

    return 0;
}

Explanation

Here, we have an array of 'n' integers to which we have used malloc() function. After allocating memory for the array, further operations can be performed as shown in the example. At last, we free up the memory by using the free() function which is also an important part of releasing the allocated memory so as to prevent any leaking of the memory.

Output

Allocated memory contents:
0 10 20 30 40

Advantages of malloc() in C Programming

There are various advantages to using malloc() in C programming. Some of them are discussed below:
  1. Firstly, the biggest advantage is that it allows the developer to allocate memory dynamically when the program is ready for execution
  2. malloc() function helps in efficiently managing memory as we are allocating memory only and only when it is needed so it enables us to optimize memory as well.
  3. Sometimes, we are working on large arrays and it is difficult to fit in the stack memory as it is limited but with the help of malloc() allocation of large data structures is also possible.
  4. Using malloc() function, we can also implement dynamic data structures such as linked lists, trees, graphs, etc.
  5. It also offers error handling mechanisms to detect errors and failures in the early stages and fix them as soon as possible.
  6. Through malloc(), memory is allocated dynamically that can be reused for different purposes as well within the program.
  7. It is portable too as it is a C library function that is suitable to work on different C compilers and different platforms.

Disadvantages of malloc() in C Programming

There are a few disadvantages to malloc() in C programming as well that are:
  1. All the memory allocation need manual efforts to manage the allocation properly with deallocation by using free() too.
  2. Sometimes, there are cases where the memory can be fragmented into small blocks of memory over time that can be a problem in future memory allocation.
  3. There are chances of memory leaks if we, somehow, do not use the free() function to deallocate the allocated memory.
  4. It is a dynamic function which also makes it error prone.
  5. Memory can be corrupted in some cases where pointers are not correctly used.

Difference Between Static and Dynamic Memory Allocation

Static Memory AllocationDynamic Memory Allocation
Static memory allocation occurs at compile time.Dynamic memory allocation occurs at runtime.
It cannot be deallocated during runtime and remains available throughout.It is deallocated using the free() function.
Allocated on the stack or in the global data segment.Allocated from the heap.
Flexibility is lower.It is much more flexible as compared to the other.
For example- global variables, static variables.For example- memory is allocated with the help of malloc(), calloc(), and realloc() functions.
Summary
Through this article, we learned about the malloc() function for dynamic memory allocation and how we can use it in our C programs to allocate memory dynamically. To learn C Programming from scratch, enroll in our C Programming Certification Course and get the best guide to learning C step by step with real-time examples.

FAQs

malloc () and calloc () in C are functions that are typically used for dynamic memory allocation where malloc() is used for allocating specified number of bytes in array and calloc() is used for allocating memory for an array of elements.

The syntax of malloc() is:
void* malloc(size_t size);
where size is used to specify the number of bytes.

All the memory allocation functions including malloc() in C are declared in the header file that is <stdlib.h>.

malloc() and free() are functions in C programming where malloc() is used for memory allocation and free(), on the contrary, is used for memory deallocation.

malloc() is considered faster than calloc() as calloc() allocates memory with initializing it to zero while there is no such need of initialization with malloc().
Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
ASP.NET Core Certification TrainingNov 08MON, TUE, WED, THU, FRI
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
Azure Developer Certification TrainingNov 09SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
.NET Solution Architect Certification TrainingNov 09SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
.NET Microservices Certification TrainingNov 09SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
Microsoft Azure Cloud Architect with AINov 10SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core Certification TrainingNov 10SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Angular Certification TrainingNov 17SAT, SUN
Filling Fast
06:00PM to 08:00PM (IST)
Get Details
Software Architecture and Design TrainingNov 24SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
.NET Solution Architect Certification TrainingNov 24SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Accept cookies & close this