为什么释放calloc需要两个参数,malloc的只有一个? [英] Why does calloc require two parameters and malloc just one?

查看:643
本文介绍了为什么释放calloc需要两个参数,malloc的只有一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是非常麻烦的,我写的释放calloc(1,sizeof的(MYSTRUCT))所有的时间。我不想使用类似包装这个方法等。我的意思是我想知道两个参数给了我一个想法?如果它给的东西,为什么不的malloc 有两个参数呢?

It's very bothersome for me to write calloc(1, sizeof(MyStruct)) all the time. I don't want to use an idea like wrapping this method and etc. I mean I want to know what two parameters gives me? If it gives something, why doesn't mallochave two parameters too?

顺便说一句,我搜索了回答这个问题,但我没有找到一个很好的答案。这些问题的答案是,释放calloc 可以比的malloc 能等。

By the way, I searched for an answer to this question but I didn't find a really good answer. Those answers was that calloc can allocate larger blocks than malloc can and etc.

我看到了另一个答案释放calloc 分配的数组。随着的malloc 我可以繁殖,我会得到一个数组,我可以在一开始使用它,而 1

I saw another answer that calloc allocates an array. With malloc I can multiply and I'll get an array and I can use it without 1, at the start.

推荐答案

历史原因的。

在引入释放calloc 时的时候,的malloc 函数不存在与释放calloc 功能将提供一个元素对象正确的对齐。

At the time of when calloc was introduced, the malloc function didn't exist and the calloc function would provide the correct alignment for one element object.

的malloc 被引入之后,我们决定返回将用于任何用途(花费更多的内存)正确对齐,因此只有一个参数是必要的内存。为释放calloc 未更改API,但释放calloc 现在也返回内存用于任何用途正确对齐。

When malloc was introduced afterwards, it was decided the memory returned would be properly aligned for any use (which costs more memory) and so only one parameter was necessary. The API for calloc was not changed but calloc now also returns memory properly aligned for any use.

编辑:

请参阅从 @JimBalter

我就介绍的malloc 的第一条语句和释放calloc 可能是完全错误的。

My first statement regarding the introduction of malloc and calloc may be totally wrong.

另外的真正原因也可能是很好无关对齐。 ç历史已经由编译器实现者发生了很大变化。 的malloc 释放calloc 可能来自不同的组/编译器实现者,这可以解释API差异。实际上我赞同这种解释的真正原因。

Also the real reasons could also be well unrelated to alignment. C history has been changed a lot by compiler implementers. malloc and calloc could come from different groups / compilers implementers and this would explain the API difference. And I actually favor this explanation as the real reason.

这篇关于为什么释放calloc需要两个参数,malloc的只有一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆