差异内存块布局由malloc和释放calloc分配呢? [英] Difference in memory block layout allocated by malloc and calloc?

查看:162
本文介绍了差异内存块布局由malloc和释放calloc分配呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

释放calloc 中分配 NUM 块,每块大小尺寸的:

无效*释放calloc(为size_t NUM,为size_t大小);​​

分配空间用于存储阵列
  分配的内存块的NUM元素的数组,每个大小字节长,它的所有位初始化为零。

Allocate space for array in memory Allocates a block of memory for an array of num elements, each of them size bytes long, and initializes all its bits to zero.

在此相反, 的malloc 分配的大小的内存一块尺寸

的void * malloc的(为size_t大小);​​

分配的内存块
  分配的存储器大小字节的块,返回一个指向该块的开头。

Allocate memory block Allocates a block of size bytes of memory, returning a pointer to the beginning of the block.

有(按释放calloc 除了零初始化)两者之间有什么区别?


Is there any difference between both (except for the zero-initialization by calloc)?

这是什么释放calloc通过 NUM 的内存块确切指的是在实践中返回的内存区域是连续为好。

What does calloc means exactly by num blocks of memory as in practice the returned memory region is contiguous as well.

我相信,必须有一定的差异,否则便没有太大的意义定义两个不同的接口,这些方法?

I believe there has to be some difference, otherwise it wouldn't make much sense to define two different interfaces for these methods?

推荐答案

在实践中,他们做同样的事情。释放calloc的优点是良好的实现将执行溢出检测时,需要做乘法,以确定您需要多少内存。

In practice they do the same thing. The advantage of calloc is that good implementations will perform an overflow detection when doing the multiplication needed to determine how much memory you need.

如果你做这样的事情:

void *
calloc(size_t nmemb, size_t size)
{
    size_t sz = nmemb * size;
    void *res = malloc(sz);

SZ可能不会最终被你希望它是什么。然后的malloc分配会比预期呼叫者少得多,但主叫方可以结束治疗返回的面积足够大。这导致堆溢出将所有的安全问题,通常有。

'sz' might not end up being what you expect it to be. malloc will then allocate much less than the caller expected, but the caller can end up treating the returned area as large enough. This leads to heap overflows will all the security implications that usually has.

这篇关于差异内存块布局由malloc和释放calloc分配呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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