c - 在 C 函数中需要 "nmem"和 "size"参数吗?

标签 c linux memory parameters

Possible Duplicate:
c difference between malloc and calloc
Why does calloc require two parameters and malloc just one?

我注意到许多 C 函数调用尤其是处理内存或文件操作的函数调用,但并非所有函数都使用这两个参数。例如 malloc 传递了一个参数,即所需内存空间的大小(以字节为单位)。另一方面,Calloc 被传递了两个参数,一个元素的字节大小和元素的数量(大小和 nmem)。还有其他函数也使用这些大小和 nmem 参数。

基本上 calloc 调用将分配与调用 malloc(nmemsize) 相同的内存量,因此真正发生的只是星号 () 被替换为逗号 (,)。至少这是我能从我工作的更高层次上知道的全部内容。我看不出调用 calloc(1, nmemsize)、calloc(nmemsize, 1) 或 calloc(nmem, size) 有什么不同。

在较低级别上是否确实发生了某些事情,使得调用例如 calloc(1, nmem*size) 与 calloc(nmem, size) 根本不同?

编辑:我知道 calloc 和 malloc 之间的功能区别。我对为什么参数存在差异感兴趣。还有其他函数使用 2 个大小参数作为总大小(fread、fwrite 等)。我不关心具体的函数,而是为什么函数中使用的总大小有两个参数,而实际上总大小变成了两个参数相乘。我发现大多数情况下,当我使用这些函数时,我在“size”参数中使用我需要的大小,在“nmem”(有时是“count”等)参数中使用“1”。

最佳答案

在对该问题的评论中,我写道 calloc() 可以在重要的平台上实现更好的内存对齐。我还没有找到任何支持(还)的东西。我很确定这是 VMS/VAXC 编译器的一个特性,但它的来源很少。


不过,我确实发现calloc()alloc()是同时出现的,在1975年5月Unix V6的发布。在V5中,发布了11 个月前,两个功能都不存在;内核和运行时库(以及汇编器和 C 编译器)是用汇编语言编写的。

在 V6 版本中,calloc is implemented作为四行源代码模块:

calloc(n, s)
{
return(alloc(n*s));
}

calloc() 不清除分配的内存;见 alloc() ,并且在 V6 中没有 calloc()man 页面;然而 man page for alloc() :

DESCRIPTION
Alloc and free provide a simple general-purpose core management package. Alloc is given a size in bytes; it returns a pointer to an area at least that size which is even and hence can hold an object of any type. The argument to free is a pointer to an area previously allocated by alloc; this space is made available for further allocation.

Needless to say, grave disorder will result if the space assigned by alloc is overrun or if some random number is handed to free.

The routine uses a first-fit algorithm which coalesces blocks being freed with other blocks already free. It calls sbrk (see "break (II))" to get more core from the system when there is no suitable space already free.

DIAGNOSTICS
Returns -1 if there is no available core.

BUGS
Allocated memory contains garbage instead of being cleared.

内存耗尽时连NULL都不返回!

calloc() 与其他几个 improvements 一起于 1979 年 1 月首次正式出现在 UNIX V7 中。 :

  • calloc() 清除返回的内存。
  • alloc() 重命名为 malloc()
  • realloc()出现了
  • 在内存耗尽或堆错误的情况下,函数“返回空指针 (0)”

关于c - 在 C 函数中需要 "nmem"和 "size"参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12862981/

相关文章:

c - 为什么数组变量等于它的地址?

c - C 中的 Null 终止字符数组以及使用 read 和 fgets 的区别

c - linux下如何判断scanf的编码?

python - 我有 Numpy 32 位还是 64 位?

.net - 可视化大对象堆碎片

c++ - 缓存在处理设备时会有限制吗?

c - 两个正则表达式之间的区别?

php - Laravel 5 没有收到任何错误日志

Linux 删除超过 1 年的文件夹和超过 3 个文件

java - Java 中的内存泄漏(在 while 循环中)