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

13 apr. 2024
Advanced
144 Views
7 min read  

malloc() Function in C: An Overview

malloc() Function in C plays an important part in the process of Dynamic Memory Allocation that allows the user to allocate memory in blocks of specific sizes. In this C Tutorial, we'll learn more about What is Dynamic Memory Allocation, Define malloc() in C Programming with Example Program. 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. There are 4 kinds of functions that 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(), that 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 got to 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 free() function that is also an important part to release 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 early stages and fix it as soon as possible.
  6. Through malloc(), memory is allocated dynamically that can be reused after for different purpose as well within the program.
  7. It is portable too as it is a C library functions 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 fragmentated 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 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 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 allocated with the help of malloc(), calloc(), and realloc() functions.
Summary
Through this article, we learnt about 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 learn C step by step with real time examples.

FAQs

Q1. What is malloc () and calloc () in C?

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.

Q2. What is the syntax of malloc?

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

Q3. Which file is malloc () in C?

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

Q4. What are malloc () and free ()?

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.

Q5. Which is faster malloc or calloc?

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