Difference Between malloc() and calloc() with Examples https://www.skillvertex.com/blog Fri, 10 May 2024 11:38:35 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 https://www.skillvertex.com/blog/wp-content/uploads/2024/01/favicon.png Difference Between malloc() and calloc() with Examples https://www.skillvertex.com/blog 32 32 Difference Between malloc() and calloc() with Examples https://www.skillvertex.com/blog/difference-between-malloc-and-calloc-with-examples/ https://www.skillvertex.com/blog/difference-between-malloc-and-calloc-with-examples/#respond Fri, 10 May 2024 11:38:35 +0000 https://www.skillvertex.com/blog/?p=3153 Read more]]>

Table of Contents

Difference Between malloc() and calloc() with Examples

The two functions such as malloc () and calloc() are library functions that can allocate dynamically. Dynamic refers to the memory that is allocated during the run time(execution of the program) from the heap segment.

Initialization

malloc() will allocate a memory block of the provided size(in bytes) and then it can return a pointer to the beginning of the block. Malloc() won’t initialize the memory. Whereas, if you attempt to read from the allocated memory without even initializing it, then it can show undefined behavior. This meant the value that you read will be garbage values.

The calloc() function in C and C++ is used to allocate memory for an array of elements and initializes all the bytes in the allocated memory to zero. It takes two arguments: the number of elements to allocate memory for and the size of each element in bytes. calloc() then returns a pointer to the allocated memory block.

Because calloc() initializes all the bytes to zero, if you try to read the values from the allocated memory without explicitly assigning values to them, you will indeed get 0 or equivalent representations for the data type you are using. This behavior is different from the malloc() function, which allocates memory but does not initialize it, so the values in the memory block may contain arbitrary data.

Parameters

The malloc() function in C and C++ takes a single argument, which is the number of bytes to allocate. It returns a pointer to a block of memory that is large enough to store the specified number of bytes. malloc() does not initialize the memory it allocates, which means the contents of the allocated memory are undefined, and you need to explicitly initialize it if needed.

calloc() indeed takes two arguments:

  1. The number of blocks or elements to be allocated.
  2. The size of each block or element in bytes.

Return Value

Both malloc() and calloc() return a pointer to the allocated memory block on successful allocation. If the allocation fails for any reason, they return a NULL pointer to indicate failure. It’s important to check the returned pointer to ensure that the allocation was successful before attempting to use the allocated memory.

Example

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

malloc()calloc()
Malloc() refers to a function which can create one block of memory of a fixed sizeCalloc() is a function that will assign a specified number of blocks of memory to single variable
It can only take one segment.It will take only two segments.
Malloc() will be faster than calloc ().calloc () is comparatively slower than mall0c()
It has more time efficiencycalloc() will have very low time efficiency.
Syntax: void*
malloc(size_t size;
Syntax : void* calloc(size_t num, size_t size);
It won’t initialize the memory to zero.It will initialize the memory to zero
It won’t add any extra memory overheadcalloc() will add extra memory overhead.

FAQ- Difference Between malloc() and calloc() with Examples

Q1. What is the return type of malloc () or calloc ()?

Ans. malloc() and calloc() will returnĀ void *

Q2. What is the syntax of malloc?

Ans. ptr = (int*) malloc(100 * sizeof(int));
It allocates memory for 100 integers, and since the size of an int is typically 4 bytes on many systems, this will allocate 400 bytes of memory. The pointer ptr holds the address of the first byte in the allocated memory, which is the starting address of the block of 400 bytes.

Q3. What is difference between malloc and new?

Ans. new is a C++ operator for dynamic memory allocation, initializing objects and returning the exact data type.
malloc() is a C and C++ library function for general memory allocation, not initializing objects, and returning void*

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

]]>
https://www.skillvertex.com/blog/difference-between-malloc-and-calloc-with-examples/feed/ 0