在已分配的内存块上的calloc是否调用重复分配?

时间:2018-12-09 15:17:03

标签: c

我已经为1024个char元素分配了一块内存。 *p指向其第一个地址。
现在我要将所有值都设置为零。如果我要使用
p = (char *) calloc(1024, sizeof(char))
,它将重用已经分配的内存块,还是在其他地方另外分配1024个新字节并更改地址*p指向?如果是这样,那么旧块会发生什么?因为我真的无法再对其调用free()

1 个答案:

答案 0 :(得分:2)

  

在已分配的内存块上的calloc会调用重复的分配吗?

不,不是。您会丢失旧的内存位置。

  

它会重用已经分配的内存块还是我会分配1024个新字节?

再次,不,不会。您将获得一个新的内存位置。

  

旧块会发生什么?

将存在内存泄漏,因为无法再次访问它。

  

我真的无法再对其打free()

您在这里。

手册页上显示:

DESCRIPTION
       operation is performed.

       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, or a unique pointer value that can later be
       successfully passed to free().


RETURN VALUE
       The malloc() and calloc() functions return a pointer to the allocated  memory,  which  is
       suitably aligned for any built-in type.  On error, these functions return NULL.  NULL may
       also be returned by a successful call to malloc() with a size of zero, or by a successful
       call to calloc() with nmemb or size equal to zero.
相关问题