Difference between malloc and calloc?

2018-12-31 07:18发布

What is the difference between doing:

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

or:

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

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

标签: c malloc calloc
13条回答
低头抚发
2楼-- · 2018-12-31 07:59
char *ptr = (char *) malloc (n * sizeof(char));

just allocates n bytes of memory without any initialization (ie; those memory bytes will contain any garbage values).

char *ptr = (char *) malloc (n, sizeof(char));

However, calloc() method in c does the initialization as 0 value for all the occupied memory bytes in addition to the function that malloc() does.

But apart from that, there is a very important difference. While calling malloc(x) it will allocate the memory (equals to x blocks) and return the pointer to the first byte allocated. However, it will not verify if exactly x blocks of memory are allocated. This will lead to the case of memory overflow. However calloc() verifies the allocation size. If it fails in the allocation of memory or verification of allocated bytes, it will simply return null.

查看更多
琉璃瓶的回忆
3楼-- · 2018-12-31 08:01

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

查看更多
永恒的永恒
4楼-- · 2018-12-31 08:05

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.

查看更多
无与为乐者.
5楼-- · 2018-12-31 08:08

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/

查看更多
与君花间醉酒
6楼-- · 2018-12-31 08:09

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.

查看更多
梦该遗忘
7楼-- · 2018-12-31 08:12

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:

data_type ptr = (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:

data_type ptr = (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)));

Similarity:

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

查看更多
登录 后发表回答