Difference between malloc and calloc (malloc vs calloc)

Difference between malloc and calloc (malloc vs calloc)

The basic difference between malloc and calloc function is that calloc() takes two arguments and the space is initialized to all bits zero while malloc takes only one argument and the space value is indeterminate.

Both malloc and calloc are memory management functions which use to allocate the memory dynamically. In C language, calloc() gives you a zero-initialized buffer, while malloc() leaves the memory uninitialized.

Before going to see the difference between malloc and calloc library functions let see some basic information about these functions. If you are new in C programming, I have already written a brief article on dynamic memory allocation you can see.

malloc function in C:

The malloc is a memory management function that allocates memory at run time. It allocates space for an object whose size is specified by size and whose value is indeterminate. Below see the syntax of the malloc function.

Syntax of malloc:

//Syntax of malloc function in C


void *malloc(size_t size);

Parameters:

size => number of bytes to allocate

Return value:

On success, the malloc function returns a pointer to the allocated space. To avoid a memory leak, you must deallocate the allocated memory with free() or realloc(). On failure, returns a null pointer.

 

Some important points related to malloc:

1. malloc function declared in stdlib.h header file.

2. The malloc function takes one argument.

3. The malloc function allocates space for an object whose size is specified by size.

4. The value of the allocated space is indeterminate. It means not initialize the allocated memory with zero ( 0 ).

5. If there is no space available, the malloc function return NULL.

Example Code,

In the below code, I am allocating dynamic memory using the malloc function and writing some characters. After writing the characters I am reading the same and displaying them on the console screen.

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

int main()
{
    char* ptr = NULL;

    // malloc() allocate the memory for 10 characters
    // containing garbage values
    ptr = (char*)malloc(10 * sizeof(char)); // 10*1bytes = 10 bytes

    if(ptr == NULL)
    {
        return (0);
    }
    printf("Enter the name = ");
    fgets(ptr,9,stdin);

    printf("Read data = %s\n\n",ptr);

    // Deallocates memory previously allocated by malloc() function
    free(ptr);

    return (0);
}

Output:

Enter the name = Amlendra
Read data = Amlendra

 

 

calloc function in C:

The calloc is also a memory management function and it also allocates the memory at run time. It allocates space for an array of nmemb objects, each of whose size is size. The space is initialized to all bits zero. Below see the syntax of the calloc function.

Syntax of calloc:

//Syntax of calloc function in C


void *calloc(size_t nmemb, size_t size);

 

Some important points related to calloc:

1. calloc function declared in stdlib.h header file.

2. The calloc function takes two arguments.

3. The calloc function allocates space for an array of nmemb objects, each of whose size is object_size.

4. Initializes all allocated space bits with zero ( 0).

5. The calloc function returns either a null pointer or a pointer to the allocated space.

Example code,

In the below code, I am allocating dynamic memory using the calloc function and writing some characters. After writing the characters I am reading the same and displaying on the console screen.

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

int main()
{
    char* ptr = NULL;

    // calloc() allocate the memory for 10 characters and
    // set 0 to all of them
    ptr = (char*)calloc(10, sizeof(char));
    if(ptr == NULL)
    {
        return (0);
    }
    printf("Enter the name = ");
    fgets(ptr,9,stdin);

    printf("Read data = %s\n\n",ptr);

    // Deallocates memory previously allocated by malloc() function
    free(ptr);

    return (0);
}

Output:

Enter the name = Amlendra
Read data = Amlendra

 

 

Note: If you don’t want to initialize the allocated memory with zero, It would be better to use malloc() over calloc().

 

Difference between malloc and calloc function ( malloc vs calloc):

In the below chart, I am explaining the difference between malloc and calloc functions.

BASIS OF COMPARISON

MALLOC()

CALLOC()

Syntax void *malloc(size_t size); void *calloc(size_t nmemb, size_t object_size);
No of blocks Assigns single block of demanded memory. Assigns multiple blocks of the requested memory.
No.of Arguments It takes one argument. It takes two arguments.
Initialization the malloc() doesn’t initialize the allocated memory. The allocated memory is initialized to zero by using calloc().
Default value Indeterminate Value. Zero is the default value.
Manner of Allocation malloc() function allocates memory of size ‘size’ from the heap. calloc() function allocates memory the size of which is equal to nmemb* object_size.
Speed Fast Comparatively slow.

 

FAQs related to malloc,calloc, and realloc functions:

In this article, I am also describing some frequently ask questions related to malloc and calloc which generally ask by freshers and experienced developers. If you have any questions related to the malloc and calloc please write the comment in the comment box.

Is it better to use malloc () or calloc ()?

The calloc function initialize the allocated memory with 0 but malloc doesn’t. So the memory which is allocated by the malloc has the garbage data. In another word you can say that calloc is equal to the combination of malloc and memeset.

See the below expression,

ptr = calloc(nmember, size);  //is essentially equivalent to
ptr = malloc(nmember * size);
memset(ptr, 0, (nmember * size));

 

Note: If you don’t want to initialize the allocated memory with zero, It would be better to use malloc over calloc.

 

What is the return value of malloc (0)?

If the size of the requested space is zero, the behavior will be implementation-defined. The return value of the malloc could be a null pointer or it shows the behavior like that size is some nonzero value. So you must never use the malloc(0) in your C program.

Let see an example C program, where I am allocating memory using the malloc with size 0.

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

int main (void)
{
    int *piBuffer = NULL;
    //allocating memory using
    //the malloc with size 0.
    piBuffer = malloc(0);
    //make sure piBuffer is valid or not
    if (piBuffer == NULL)
    {
        // allocation failed, exit from the program
        fprintf(stderr, "Out of memory!\n");
        exit(1);
    }
    *piBuffer = 10;
    printf("%d\n",*piBuffer);
    free(piBuffer);
    return 0;
}

 

 What is dynamic memory fragmentation?

The memory management function gives the guaranteed that allocated memory would be aligned with the object. The fundamental alignment is less than or equal to the largest alignment that’s supported by the implementation without an alignment specification.

One of the major problems with dynamic memory allocation is fragmentation, basically, fragmentation occurred when the user does not use the memory efficiently. There are two types of fragmentation, external fragmentation, and internal fragmentation.

The external fragmentation is due to the small free blocks of memory (small memory hole) that are available on the free list but the program not able to use it. There are different types of free list allocation algorithms that used the free memory block efficiently.

Consider a scenario where the program has 3 contiguous blocks of memory and the user frees the middle block of memory. In that scenario, you will not get a memory, if the required block is larger than a single block of memory. See the below Image,

External Fragmentation

Internal fragmentation is the wastage of memory that is allocated for rounding up the allocated memory and in bookkeeping (infrastructure). The bookkeeping memory is used to keep the information of allocated memory.

Whenever we called malloc function then it reserves some extra bytes (depend on implementation and system) for bookkeeping. These extra bytes are reserved for each call of malloc and become the cause of internal fragmentation.

Let see an example program to understand the internal fragmentation,

In the below code, a programmer may think that the system will allocate 8 *100 (800) bytes of memory but due to bookkeeping, (I assumed bookkeeping bytes is 8) system will allocate 8*100 extra bytes. You can see how internal fragmentation is waisting of heap memory. The given example is only for understanding, the actual behavior is the implementation-dependent.

char *acBuffer[100];
int main()
{
    int iLoop = 0;
    while(iLoop < 100)
    {
        acBuffer[iLoop ] =  malloc(8);
        ++iLoop
    }
}

 

Who is faster malloc or calloc in C?

In short, malloc is faster than calloc in C. If you aren’t going to ever read memory before writing it, use the malloc function. In my opinion, if you just want to copy some stuff or do something that doesn’t require zeros initialized memory, use the malloc function.

Why is malloc preferred over Calloc?

I have already described in the above question that malloc is faster than calloc.

 

Can we deallocate the memory using the realloc()?

Yes, you can.

 

What happened if called the free function twice?

The behavior is undefined.

 

Can free the same memory multiple times?

The behavior is undefined.

 

What happens if the free function is called on a space which has been deallocated by the free or realloc?

If the space has been deallocated by a call to free or realloc, the behavior is undefined.

 

Do I cast the result of malloc in C?

In C, you don’t need to cast the return value of malloc. The pointer to void returned by malloc is automagically converted to the correct type.

 

What really happens when you don’t free after malloc?

It could be the cause of a memory leak. But the most modern operating systems will recover all the allocated memory space after a program exits. it is really good practice to free the allocated memory after use.

 

How does free know how much to free?

When you call the memory management functions (malloc, calloc, or realloc)  and specify the amount of memory to allocate. The amount of memory actually used is slightly more than this and includes extra information (bookkeeping) that records how big the allocated block is.

 

Why does free() in C not take the number of bytes to be freed?

The allocated pointer already contains the information about the allocated memory. It is the reason free() in C does not take the number of bytes to be freed.

 

Recommended Articles for you:



2 comments

Leave a Reply

Your email address will not be published. Required fields are marked *