The Wayback Machine - https://web.archive.org/web/20240901093656/https://www.geeksforgeeks.org/difference-between-malloc-and-calloc-with-examples/
Open In App

Difference Between malloc() and calloc() with Examples

Last Updated : 21 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The functions malloc() and calloc() are library functions that allocate memory dynamically. Dynamic means the memory is allocated during runtime (execution of the program) from the heap segment.

Initialization

malloc() allocates a memory block of given size (in bytes) and returns a pointer to the beginning of the block. malloc() doesn’t initialize the allocated memory. If you try to read from the allocated memory without first initializing it, then you will invoke undefined behavior, which usually means the values you read will be garbage values.

calloc() allocates the memory and also initializes every byte in the allocated memory to 0. If you try to read the value of the allocated memory without initializing it, you’ll get 0 as it has already been initialized to 0 by calloc().

Parameters

malloc() takes a single argument, which is the number of bytes to allocate.

Unlike malloc(), calloc() takes two arguments:

  1. Number of blocks to be allocated. 
  2. Size of each block in bytes.

Return Value

After successful allocation in malloc() and calloc(), a pointer to the block of memory is returned otherwise NULL is returned which indicates failure.

Example

The below C code demonstrates the difference between malloc and calloc functions to allocate dynamic memory.

C
// C code that demonstrates the difference
// between calloc and malloc
#include <stdio.h>
#include <stdlib.h>

int main()
{
    // Both of these allocate the same number of bytes,
    // which is the amount of bytes that is required to
    // store 5 int values.

    // The memory allocated by calloc will be
    // zero-initialized, but the memory allocated with
    // malloc will be uninitialized so reading it would be
    // undefined behavior.
    int* allocated_with_malloc = malloc(5 * sizeof(int));
    int* allocated_with_calloc = calloc(5, sizeof(int));

    // As you can see, all of the values are initialized to
    // zero.
    printf("Values of allocated_with_calloc: ");
    for (size_t i = 0; i < 5; ++i) {
        printf("%d ", allocated_with_calloc[i]);
    }
    putchar('\n');

    // This malloc requests 1 terabyte of dynamic memory,
    // which is unavailable in this case, and so the
    // allocation fails and returns NULL.
    int* failed_malloc = malloc(1000000000000);
    if (failed_malloc == NULL) {
        printf("The allocation failed, the value of "
               "failed_malloc is: %p",
               (void*)failed_malloc);
    }

    // Remember to always free dynamically allocated memory.
    free(allocated_with_malloc);
    free(allocated_with_calloc);
}

Output
Values of allocated_with_calloc: 0 0 0 0 0 
The allocation failed, the value of failed_malloc is: (nil)

Difference between malloc() and calloc() in C

Let us see the differences in a tabular form:

S.No. 

malloc()

calloc()

1.

malloc() is a function that creates one block of memory of a fixed size.calloc() is a function that assigns a specified number of blocks of memory to a single variable.

2.

malloc() only takes one argumentcalloc() takes two arguments.

3.

malloc() is faster than calloc.calloc() is slower than malloc()

4.

malloc() has high time efficiencycalloc() has low time efficiency

5.

malloc() is used to indicate memory allocationcalloc() is used to indicate contiguous memory allocation

6.

Syntax : void* malloc(size_t size);Syntax : void* calloc(size_t num, size_t size);

7.

malloc() does not initialize the memory to zerocalloc() initializes the memory to zero

8.

malloc() does not add any extra memory overheadcalloc() adds some extra memory overhead

Related Articles


Previous Article
Next Article

Similar Reads

Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations.  As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example,  If there is
9 min read
what happens when you don't free memory after using malloc()
Pre-requisite: Dynamic memory allocation in CThe "malloc" or "memory allocation" method is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It initializes each block with a default garbage value.Syntax: ptr = (cast-type*) malloc(byte-
3 min read
Alternative of Malloc in C
An array in C or C++ is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They are used for storing similar types of elements as the data type must be the same for all elements. They can be used to store the collection of primitive data types such as int, float, double, char
4 min read
malloc() vs new
Following are the differences between malloc() and operator new.: Calling Constructors: new calls constructors, while malloc() does not. In fact primitive data types (char, int, float.. etc) can also be initialized with new. For example, below program prints 10. C/C++ Code #include&lt;iostream&gt; using namespace std; int main() { // Initialization
1 min read
Function Interposition in C with an example of user defined malloc()
Function interposition is the concept of replacing calls to functions in dynamic libraries with calls to user-defined wrappers. What are applications? We can count number of calls to function. Store caller's information and arguments passed to function to track usage. Detect memory leak, we can override malloc() and keep track of allocated spaces.
3 min read
Difference between Argument and Parameter in C/C++ with Examples
Argument An argument is referred to the values that are passed within a function when the function is called. These values are generally the source of the function that require the arguments during the process of execution. These values are assigned to the variables in the definition of the function that is called. The type of the values passed in
4 min read
Difference between Struct and Enum in C/C++ with Examples
Structure in C++ A structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. The ‘struct’ keyword is used to create a structure. Syntax: struct structureName{ member1; member2; member3; . . . memberN; }; Below is the implementation: C/C++ Code #inc
3 min read
Difference between #include and #include" " in C/C++ with Examples
Pre-requisites: Header files in C/ C++ and its uses The difference between the two types is in the location where the preprocessor searches for the file to be included in the code. #include &lt;filename&gt; // Standard library header #include "filename" // User defined header #include&lt;filename&gt; #include&lt;&gt; is for pre-defined header files
4 min read
Difference between Iterator and Enumeration in Java with Examples
When working with collections in Java, traversing through elements efficiently is key. Two tools you might encounter are Iterator and Enumeration. Both are used to go through collections, but they serve different purposes and come with distinct features. What is an Iterator?An Iterator is a universal tool in Java that allows you to traverse through
3 min read
Difference and Similarities between PHP and C
PHP is a server-side scripting language designed specifically for web development. It can be easily embedded in HTML files and HTML codes can also be written in a PHP file. The thing that differentiates PHP from a client-side language like HTML is, PHP codes are executed on the server whereas HTML codes are directly rendered on the browser. C is a
3 min read
Difference between ++*p, *p++ and *++p
Predict the output of following C programs. C/C++ Code // PROGRAM 1 #include &lt;stdio.h&gt; int main(void) { int arr[] = {10, 20}; int *p = arr; ++*p; printf(&quot;arr[0] = %d, arr[1] = %d, *p = %d&quot;, arr[0], arr[1], *p); return 0; } C/C++ Code // PROGRAM 2 #include &lt;stdio.h&gt; int main(void) { int arr[] = {10, 20}; int *p = arr; *p++; pri
2 min read
What’s difference between “array” and “&amp;array” for “int array[5]” ?
If someone has defined an array such as “int array[5]”, what’s the meaning of “array” or “&amp;array”? Are they both same or are they different? You might be tempted to think that they both would point to the very first element of the array i.e. they both will have same address. Let us find out! To check this, the very first thing that comes to min
4 min read
Difference between strlen() and sizeof() for string in C
sizeof() Sizeof operator is a compile time unary operator which can be used to compute the size of its operand. The result of sizeof is of unsigned integral type which is usually denoted by size_t.sizeof can be applied to any data-type, including primitive types such as integer and floating-point types, pointer types, or compound datatypes such as
2 min read
Difference Between Constants and Variables in C
The constants and variables in C are both used to store data. So it is essential to know the difference between the variables and constants in C so that we can decide which one to use based on the situation. In this article, we will discuss the basic difference between a constant and a variable in C language. Variables in C A variable in simple ter
3 min read
Difference between Header file and Library
Header Files: The files that tell the compiler how to call some functionality (without knowing how the functionality actually works) are called header files. They contain the function prototypes. They also contain Data types and constants used with the libraries. We use #include to use these header files in programs. These files end with .h extensi
3 min read
Difference between fundamental data types and derived data types
In computer programming, data type is a classification that specifies to compiler or interpreter which type of data user is intending to use. There are two types of data types - Primitive/Fundamental data type: Each variable in C/C++ has an associated data type. Each data type requires different amounts of memory and has some specific operations wh
8 min read
Difference between Static and Shared libraries
In programming, a library is a collection of pre-compiled pieces of code that can be reused in a program. Libraries simplify life for programmers, in that they provide reusable functions, routines, classes, data structures and so on which they can be reused in the programs. Static Libraries: A Static library or statically-linked library is a set of
2 min read
Difference between Java and C language
Here are some of the differences between Java and C language. C is much faster than Java Java is slower than C due to overhead. C Java C was developed by Dennis M. Ritchie between 1969 and 1973.Java was developed by James Gosling in 1995.C is a Procedural Programming Language.Java is Object-Oriented language.C is more procedure-oriented.Java is mor
3 min read
Difference between C and Python
Here are some of the differences between C and Python. CPythonAn Imperative programming model is basically followed by C.An object-oriented programming model is basically followed by Python.Variables are declared in C.Python has no declaration.C doesn’t have native OOP.Python has OOP which is a part of the language.Pointers are available in C langu
2 min read
Difference between Structure and Array in C
Array in C An array is collection of items stored at contiguous memory locations. Structure in C A structure is a user defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. Difference between Structure and Array ARRAYSTRUCTUREArray refers to a collection consistin
2 min read
Difference between pointer to an array and array of pointers
Pointer to an array: Pointer to an array is also known as array pointer. We are using the pointer to access the components of the array. int a[3] = {3, 4, 5 }; int *ptr = a; We have a pointer ptr that focuses to the 0th component of the array. We can likewise declare a pointer that can point to whole array rather than just a single component of the
4 min read
Difference between scanf() and gets() in C
scanf()It is used to read the input(character, string, numeric data) from the standard input(keyboard).It is used to read the input until it encounters a whitespace, newline or End Of File(EOF). For example see the following code: C/C++ Code // C program to see how scanf() // stops reading input after whitespaces #include &amp;lt;stdio.h&amp;gt; in
3 min read
Difference between C and C#
C language: C language is a middle programming language that was developed at Bell research lab in 1972 by Dennis Ritchie. C language combines the properties of low level and high-level language. therefore its thought-about a middle programming Language. C may be a high-level classical kind programming language that permits you to develop computer
2 min read
Difference between Static variables and Register variables in C
static variables Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope. Syntax: static data_type var_name = var_value; register variables Registers are faster than memory to access
2 min read
Difference between Type Casting and Type Conversion
1. Type Casting: In typing casting, a data type is converted into another data type by the programmer using the casting operator during the program design. In typing casting, the destination data type may be smaller than the source data type when converting the data type to another data type, that's why it is also called narrowing conversion. Synta
3 min read
Difference between C and Objective C
The language C was developed in early 1970s by Dennis Ritchie for the UNIX Operating system. It a general purpose, procedural programming language. The language is used for developing system applications as well as desktop applications. To learn more about C language refer to https://www. geeksforgeeks. org/c-programming-language/ Objective C was d
4 min read
Difference between Sentinel and Counter Controlled Loop in C
Sentinel Controlled Loop A sentinel controlled loop is also called an indefinite repetition loop because the number of iterations is not known before the loop starts executing. In a sentinel controlled loop, a special value called sentinel value is used to change the loop control expression from true to false in order to determine whether to execut
3 min read
Difference between C and Dart
1. C language : C language is a programming language developed at Bell research lab in 1972 by Dennis Ritchie. C language combines the properties of low level and high-level language. C is a high-level classical kind programming language that permits to develop computer code and movable applications. 2. Dart language : Dart is an object-oriented pr
2 min read
Difference between Identifiers and Variables in C
Perquisites: Identifiers, Variables Identifiers Identifiers are used for the naming of variables, functions, and arrays. It is a string of alphanumeric characters that begins with an alphabet, or an underscore( _ ) that are used for variables, functions, arrays, structures, unions, and so on. It is also known as the user-defined word. Identifier na
2 min read
Difference between Array and Union in C
1. Array in C : An array is collection of similar data items accessed by a common name stored at continuous memory locations. The elements of an array can be accessed using indices. They can be used to store primitive data types such as int, float, double, char, etc. but all elements have to be of the same data type. Below is the picturesque repres
2 min read