Malloc in C Programming: How to Allocate Memory Dynamically
This article covers the concept of dynamic memory allocation in C programming, which allows allocating memory at runtime according to the program’s needs using functions like malloc(), calloc(), realloc(), and free(). The article focuses on the malloc() function in detail, explaining its syntax, advantages and disadvantages, and providing an example to help understand the concept of dynamic memory allocation.
Table Of Contents
Best-suited C / C++ courses for you
Learn C / C++ with these high-rated online courses
Introduction
The malloc () is a C library function for dynamic memory allocation. Dynamic memory allocation means allocating memory at the runtime per the needs of your program.
In programming, each byte is countable. Variables and arrays in C programming have static memory means they already have predefined memory by the C compiler. Integer consumes 2 bytes of memory, float takes 4 bytes, and so on.
When you declare an array of any type, the C compiler will automatically allocate contiguous memory of its size. Problems arise:
- When a program utilizes only some part of an array while wasting the remaining memory.
- When the array size is small, the program wants more space.
The dynamic allocation functions in C programs help in these situations as you can define the array size at the runtime.
In this article, we will learn about malloc () and how to use it in a C program. This article will also help you to understand the difference between static and dynamic memory allocation.
Also explore: C Programming Online Courses & Certifications
What is Dynamic Memory Allocation
Dynamic Memory Allocation is allocating memory to the C variables at runtime. Such memory allocation helps by increasing or decreasing the memory space at the runtime per the requirements.
In C programming, heaps are used to allocate memory dynamically. Programmers can manually allocate memory to the variable or group of variables using <stdlib.h> header file.
C programming provides four library functions for dynamic memory allocation.
malloc()
It is used to allocate memory dynamically for a defined size. We will discuss it in detail in the coming sections of the article
calloc()
It stands for contiguous memory allocation. calloc() is used to allocate several memory spaces.
realloc()
It is used to reallocate memory to already used functions malloc () and calloc().
free()
This function frees up the allocated memory by the dynamic memory allocation functions.
The malloc() in C Programming
malloc() is one word for memory allocation. It is one of the dynamic memory allocation functions defined in <stdlib.h> C header file.
The malloc() is used to allocate a memory space of a certain size. You can resize the memory space at any time in the program. malloc() function uses a pointer to locate the memory address, and this pointer’s default value is null.
The malloc() uses a size of() function to define its size. sizeof() of is a predefined C function that returns the size of a variable.
For example:
int a;
printf (sizeof(a));
Its output is two as the C compiler allocates 2 bytes to integers.
The malloc() function addresses the size problem of arrays as array size is defined at the time of array declaration. This restricts the code to a fixed size. Using malloc() coders can define the array size at runtime and can increase or decrease it.
Syntax of malloc():
ptr = (cast_type *) malloc (size_type);
Here,
ptr is cast type pointer
cast_type is data type
size_type is size of the variable
For example
ptr = (int*) malloc (50 * sizeof(int));
The above statement will allocate 100 bytes of memory space. The memory space of an integer is 2, and malloc allotted 50 * 2 = 100 bytes.
The malloc() will return NULL in two cases:
- Memory space is insufficient
- The malloc() fails to assign memory.
Example of malloc in C Programming
To understand the principle of the malloc() function, we will create a C program for dynamic memory allocation.
#include<stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
//Declaring malloc() function to dynamically allocate memory
ptr = (int*) malloc (10 * sizeof(int)); if(ptr==NULL) {
printf("Sorry....No Space. \n");
}
else
{
printf("Successful Memory Allocation \n");
//Assigning value to the pointer ptr
for(int i=1;i<=5;i++)
{
ptr[i] = i;
}
//Printing the array elements
printf("The array elements are: \n");
for(int i=1;i<=5;i++)
{
printf("%d\n", ptr[i]);
} }
}
OUTPUT
Successful Memory Allocation
The array elements are:
1
2
3
4
5
Explanation: In the above code, we declare an integer pointer to address the dynamic memory allocation by the malloc(). The “if” condition will check if the pointer ptr is NULL or not. If ptr is NULL, the program will terminate by printing the if conditional statement.
In case the “if” condition is false, the control will go to the “else” condition and use the “for” loop to insert elements to the pointer ptr and again use the “for” loop to print all the elements of the array pointer ptr.
Advantages of malloc() in C Programming
- Dynamic memory allocation helps easily use large data where memory requirement arises at any time.
- The malloc() facilitates resizing the memory at any time in the program.
- The pointer ptr points to the first element, making it similar to an array.
Disadvantages of malloc() in C Programming
- malloc() is not useful for embedded systems.
- While using the malloc() function for dynamic memory allocation, you have to remember the defined size or memory space.
- malloc() function could be more efficient.
Difference Between Static and Dynamic Memory Allocation
S.No | Static Memory Allocation | Dynamic Memory Allocation |
1. | Static memory is allocated by the C compiler. | Dynamic memory is allocated by the user. |
2. | Static memory is of fixed size and pre-defined by the C compiler. | Users can define the memory size at the run-time. |
3. | Static memory is a fixed memory. | Dynamic memory size can be changed whenever needed. |
4. | Examples of static memory are int, char, float, and array. | There are 4 library functions for dynamic memory allocation: malloc(), calloc(), realloc(), and free(). |
5. | Static memory uses stack data structure for memory allocation. | Dynamic memory uses heap data structure for memory allocation. |
6. | It is represented by an array. | It is represented by a pointer. |
Conclusion
The malloc() helps to allocate memory space at runtime while allocating a single block of memory to all inserted elements. The memory allocated by the malloc() function can be freed up using the free() function.
Static memory allocation is significant when dealing with small amounts of data as the memory wastage and size does not affect much. Working with a bulk of data enhances the importance of a single memory byte in a program, and this requirement gives meaning to dynamic memory allocation functions like malloc(), calloc(), realloc(), and free().
This article was about the meaning and use of the malloc() function in a C program. I hope you liked it and understand the malloc() concept.
Contributed by Sonal Meenu Singh
FAQs
What is malloc () and calloc () in C?
The malloc() and calloc() are per-defined functions in the C library to allocate dynamic memory. The malloc() stands for memory allocation, it allocates a single block of memory of a defined size. calloc() stands for contiguous allocation, and it allocates different memory blocks.
What is the syntax of malloc?
Syntax of malloc() is ptr = (cast_type *) malloc (size_type); In malloc() syntax, 3 variables are used. Where, ptr is the cast type pointer, cast_type is data type, and size_type is the size for the memory allocation. For example: ptr = (int*) malloc (100 sizeof(int));
What is the difference between malloc (), calloc (), and Realloc?
There are four library functions for dynamic memory allocation: calloc(), malloc(), realloc, and free(). malloc() allocates individual memory space to store data. It stands for memory allocation. calloc() stands for contiguous allocation. It allocates different memory spaces to the variables. realloc() is used to reallocate the memory defined by malloc() and calloc() functions.
What are malloc () and free ()?
The malloc() and free() are functions for dynamically allocating memory in the C program. The malloc() is similar to an array in C but does not allocate static memory with a fixed size. It uses a pointer for dynamic or runtime memory allocation. free() is another function for dynamic memory allocation. It is used to free up the allocated memory by the user.
Why use malloc instead of an array?
An array is a size bonded, and its size is defined in advance. It is not resizable and has a fixed size. The user cannot increase or decrease an array size after an array size definition. The malloc() is not size bound and is similar to an array. But you can define its size at the runtime.
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio