Difference between malloc and calloc?

What is the difference between doing:

ptr = (char **) malloc (MAXELEMS * sizeof(char *));


ptr = (char **) calloc (MAXELEMS, sizeof(char*));

When is it a good idea to use calloc over malloc or vice versa?

-------------Problems Reply------------

calloc() zero-initializes the buffer, while malloc() leaves the memory uninitialized.


Zeroing out the memory may take a little time, so you probably want to use malloc() if that performance is an issue. If initializing the memory is more important, use calloc(). For example, calloc() might save you a call to memset().

A less known difference is that in operating systems with optimistic memory allocation, like Linux, the pointer returned by malloc isn't backed by real memory until the program actually touches it.

calloc does indeed touch the memory (it writes zeroes on it) and thus you'll be sure the OS is backing the allocation with actual RAM (or swap). This is also why it is slower than malloc (not only does it have to zero it, the OS must also find a suitable memory area by possibly swapping out other processes)

See for instance this SO question for further discussion about the behavior of malloc

One often-overlooked advantage of calloc is that (conformant implementations of) it will help protect you against integer overflow vulnerabilities. Compare:

size_t count = get_int32(file);
struct foo *bar = malloc(count * sizeof *bar);


size_t count = get_int32(file);
struct foo *bar = calloc(count, sizeof *bar);

The former could result in a tiny allocation and subsequent buffer overflows, if count is greater than SIZE_MAX/sizeof *bar. The latter will automatically fail in this case since an object that large cannot be created.

Of course you may have to be on the lookout for non-conformant implementations which simply ignore the possibility of overflow... If this is a concern on platforms you target, you'll have to do a manual test for overflow anyway.

There's no difference in the size of the memory block allocated. calloc just fills the memory block with physical all-zero-bits pattern. In practice it is often assumed that the objects located in the memory block allocated with calloc have initilial value as if they were initialized with literal 0, i.e. integers should have value of 0, floating-point variables - value of 0.0, pointers - the appropriate null-pointer value, and so on.

From the pedantic point of view though, calloc (as well as memset(..., 0, ...)) is only guaranteed to properly initialize (with zeroes) objects of type unsigned char. Everything else is not guaranteed to be properly initialized and may contain so called trap representation, which causes undefined behavior. In other words, for any type other than unsigned char the aforementioned all-zero-bits patterm might represent an illegal value, trap representation.

Later, in one of the Technical Corrigenda to C99 standard, the behavior was defined for all integer types (which makes sense). I.e. formally, in the current C language you can initialize only integer types with calloc (and memset(..., 0, ...)). Using it to initialize anything else in general case leads to undefined behavior, from the point of view of C language.

In practice, calloc works, as we all know :), but whether you'd want to use it (considering the above) is up to you. I personally prefer to avoid it completely, use malloc instead and perform my own initialization.

Finally, another important detail is that calloc is required to calculate the final block size internally, by multiplying element size by number of elements. While doing that, calloc must watch for possible arithmetic overflow. It will result in unsuccessful allocation (null pointer) if the requested block size cannot be correctly calculated. Meanwhile, your malloc version makes no attempt to watch for overflow. It will allocate some "unpredictable" amount of memory in case overflow happens.

The documentation makes the calloc look like malloc, which just does zero-initialize the memory; this is not the primary difference! The idea of calloc is to abstact copy-on-write semantics for memory allocation. When you allocate memory with calloc it all maps to same physical page which is initialized to zero. When any of the pages of the allocated memory is written into a physical page is allocated. This is often used to make HUGE hash tables, for example since the parts of hash which are empty aren't backed by any extra memory (pages); they happily point to the single zero-initialized page, which can be even shared between processes.

Any write to virtual address is mapped to a page, if that page is the zero-page, another physical page is allocated, the zero page is copied there and the control flow is returned to the client process. This works same way memory mapped files, virtual memory, etc. work.. it uses paging.

Here is one optimization story about the topic: http://blogs.fau.de/hager/2007/05/08/benchmarking-fun-with-calloc-and-zero-pages/

from an article Benchmarking fun with calloc() and zero pages on Georg Hager's Blog

When allocating memory using calloc(), the amount of memory requested is not allocated right away. Instead, all pages that belong to the memory block are connected to a single page containing all zeroes by some MMU magic (links below). If such pages are only read (which was true for arrays b, c and d in the original version of the benchmark), the data is provided from the single zero page, which – of course – fits into cache. So much for memory-bound loop kernels. If a page gets written to (no matter how), a fault occurs, the “real” page is mapped and the zero page is copied to memory. This is called copy-on-write, a well-known optimization approach (that I even have taught multiple times in my C++ lectures). After that, the zero-read trick does not work any more for that page and this is why performance was so much lower after inserting the – supposedly redundant – init loop.

calloc is generally malloc+memset to 0

It is generally slightly better to use malloc+memset explicitly, especially when you are doing something like:

memset(ptr, 0, sizeof(Item));

That is better because sizeof(Item) is know to the compiler at compile time and the compiler will in most cases replace it with the best possible instructions to zero memory. On the other hand if memset is happening in calloc, the parameter size of the allocation is not compiled in in the calloc code and real memset is often called, which would typically contain code to do byte-by-byte fill up until long boundary, than cycle to fill up memory in sizeof(long) chunks and finally byte-by-byte fill up of the remaining space. Even if the allocator is smart enough to call some aligned_memset it will still be a generic loop.

One notable exception would be when you are doing malloc/calloc of a very large chunk of memory (some power_of_two kilobytes) in which case allocation may be done directly from kernel. As OS kernels will typically zero out all memory they give away for security reasons, smart enough calloc might just return it withoud additional zeroing. Again - if you are just allocating something you know is small, you may be better off with malloc+memset performance-wise.

There are two differences.
First, is in the number of arguments. malloc() takes a single argument (memory required in bytes), while calloc() needs two arguments.
Secondly, malloc() does not initialize the memory allocated, while calloc() initializes the allocated memory to ZERO.

  • calloc() allocates a memory area, the length will be the product of its parameters. calloc fills the memory with ZERO's and returns a pointer to first byte. If it fails to locate enough space it returns a NULL pointer.

Syntax: ptr_var=(cast_type *)calloc(no_of_blocks , size_of_each_block); i.e. ptr_var=(type *)calloc(n,s);

  • malloc() allocates a single block of memory of REQUSTED SIZE and returns a pointer to first byte. If it fails to locate requsted amount of memory it returns a null pointer.

Syntax: ptr_var=(cast_type *)malloc(Size_in_bytes); The malloc() function take one argument, which is the number of bytes to allocate, while the calloc() function takes two arguments, one being the number of elements, and the other being the number of bytes to allocate for each of those elements. Also, calloc() initializes the allocated space to zeroes, while malloc() does not.

There are three main differences between calloc and malloc :-
1). calloc initialize the allocated memory with 0(zero) while malloc just fill it with garbage.
And it is correctly said that : Zeroing out the memory may take a little time, so you probably want to use malloc() if that performance is an issue. If initializing the memory is more important, use calloc(). For example, calloc() might save you a call to memset().
2). calloc takes the number and type of data as arguments while malloc takes the number of bytes.
3). calloc may or may not allocate contiguous memory locations but malloc always allocate contiguous memory locations.

The calloc() function that is declared in the <stdlib.h> header offers a couple of advantages over the malloc() function.

  1. It allocates memory as a number of elements of a given size, and
  2. It initializes the memory that is allocated so that all bits are zero.

calloc will clear allotted memory to the particular allotted pointer variable

The calloc() function allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the allocated memory. The memory is set to zero. If nmemb or size is 0, then calloc() returns either NULL,

malloc(): Allocates requested size of bytes and returns a pointer first byte of allocated space

calloc(): Allocates space for an array elements, initializes to zero and then returns a pointer to memory

Difference 1: malloc() usually allocates the memory block and it is initialized memory segment. calloc() allocates the memory block and initialize all the memory block to 0.

Difference 2: If you consider malloc() syntax, it will take only 1 argument. Consider the following example below:

ptr data_type = (cast_type *)malloc(sizeof(data_type)*no_of_blocks;

Ex: If you want to allocate 10 block of memory for int type,

int *ptr = (int *) malloc(sizeof(int)*10;

If you consider calloc() syntax, it will take 2 arguments. Consider the following example below:

ptr data_type = (cast_type *)calloc(no_of_blocks, (sizeof(data_type));

Ex: if you want to allocate 10 blocks of memory for int type and Initialize all that to ZERO,

int *ptr = (int *) calloc(10, (sizeof(int));


Both malloc() and calloc() will return void* by default if they are not type casted .!

Category:c# Views:0 Time:2009-10-08
Tags: c# malloc calloc

Related post

  • I'm very confused about malloc() and calloc() on C 2010-11-21

    I've always programmed in Java, which is probably why I'm so confused about this: In Java I declare a pointer: int[] array and initialize it or assign it some memory: int[] array = {0,1,0} int[] array = new int[3] Now, in C, it's all so confusing. At

  • preferring malloc over calloc 2010-11-22

    Possible Duplicate: c difference between malloc and calloc Is there any situation where you would prefer malloc over calloc. i know both malloc and calloc allocate memory dynamically and that calloc also initializes all bits in alloted memory to zero

  • Malloc or Calloc and when 2012-11-22

    Possible Duplicate: c difference between malloc and calloc Is calloc same as malloc with memset?? or is there any difference char *ptr; ptr=(char *)calloc(1,100) or char *ptr; ptr=(char *) malloc(100); memset(ptr,0,100); --------------Solutions------

  • Difference in uses between malloc and calloc 2010-11-30

    gcc 4.5.1 c89 I have written this source code for my better understanding of malloc and calloc. I understand, but just have a few questions. dev = malloc(number * sizeof *devices); is equal to this calloc. I am not concerned about clearing the memory

  • C - Malloc or calloc-and how? 2010-04-30

    i have a text file where the first number defines the size of the arrays. I know that calloc or malloc can reserve memory, but how? this code: typedef struct alpha { int* size; char name; int tot; char line[60]; } ALPHA; fgets(line, 60, fp); tot = at

  • what is the difference between Malloc and new operator to allocate a memory? 2010-07-15

    Possible Duplicate: What is the difference between new/delete and malloc/free? I was confused when I create an object by using new operator in C++. There must be difference between malloc and new operator that would allow me to resize the memory bloc

  • free() function without malloc or calloc 2010-11-05

    quick question Can you use the free() function without having to prior call a malloc ?? ei. void someFunc( void ) { char str[6] = {"Hello"}; //some processing here .... free(str); } I get no compiling errors but Does this work or is it correct at all

  • Differences between `malloc` and `new` 2010-11-23

    Possible Duplicate: What is the difference between new/delete and malloc/free? Could someone please revise/edit the below - the differences between malloc and new - and see if everything is correct, or am I missing something or got something wrong? T

  • Regarding the differences between malloc and new in terms of their respective mechanisms of handling memory allocation? 2011-09-30

    What are the differences between malloc and new in terms of their respective mechanisms of handling memory allocation? --------------Solutions------------- malloc doesn't throw bad_alloc exepetion as new does. Because malloc doesn't throw exceptions,

  • Understanding the purpose of malloc and calloc 2011-12-11

    I'm trying to get my head around C. Reading through K&R, I am flicking back and forth trying to find where it states the situations I should obtain blocks of memory dynamically. For example, I want to have an int pointer. int *pointer; But then K

  • Is there a fundamental difference between malloc and HeapAlloc (aside from the portability)? 2011-01-03

    I'm having code that, for various reasons, I'm trying to port from the C runtime to one that uses the Windows Heap API. I've encountered a problem: If I redirect the malloc/calloc/realloc/free calls to HeapAlloc/HeapReAlloc/HeapFree (with GetProcessH

  • is there a difference between malloced arrays and newed arrays 2009-12-28

    I'm normally programming in c++, but are using some clibrary functions for my char*. Some of the manpages like for 'getline', says that input should be a malloced array. Is it ok, to use 'new' instead? I can see for my small sample that it works, but

  • Any difference between malloc and Marshal.AllocHGlobal? 2012-01-26

    I write a module in C# that exports some functions to be used in C. I need to allocate soem memory for some structs to be passed between C <-> C#. What I allocate in C I do with malloc, and in C# I do with Marshal.AllocHGlobal() (to allocate un

  • calloc v/s malloc and time efficiency 2010-04-09

    I've read with interest the post C difference between malloc and calloc. I'm using malloc in my code and would like to know what difference I'll have using calloc instead. My present (pseudo)code with malloc: Scenario 1 int main() { allocate large ar

  • C - calloc() v. malloc() 2010-08-10

    Possible Duplicate: c difference between malloc and calloc Please explain the significance of this statement, Another difference between the malloc() and calloc() functions is that the memory allocated by malloc( ) function contains garbage values, w

  • Does realloc and calloc call malloc? 2011-07-14

    This is probably an easy question but I couldn't find an answer. Is malloc internally called within realloc and within calloc? Since I am somehow counting the malloc calls, it is interesting for me. Thanks --------------Solutions------------- You sho

  • In what cases do I use malloc vs new? 2008-10-08

    I see in C++ there are multiple ways to allocate and free data and I understand that when you call malloc you should call free and when you use the new operator you should pair with delete and it is a mistake to mix the two (e.g. Calling free() on so

  • When to use Malloc instead of New 2009-04-30

    Duplicate of: In what cases do I use malloc vs new? Just re-reading this question: http://stackoverflow.com/questions/807939/what-is-the-difference-between-new-and-malloc-and-calloc-in-c-closed I checked the answers but nobody answered the question:

  • How to free() a malloc()'d structured correctly? 2010-02-02

    i have a structure malloc()'d, and after using them, i want to free() it, but my program freezes out here. Can anyone tell me, what i am doing wrong? Here is my code: struct data { char *filename; char *size; }; //primarypcs is a long type variable s

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.078 (s). 11 q(s)