0%

malloc、calloc、realloc简介

malloc

函数声明:

1
void	*malloc(size_t __size) __result_use_check __alloc_size(1);

Initialization: malloc() allocates memory block of given size (in bytes) and returns a pointer to the beginning of the block. malloc() doesn’t initialize the allocated memory. If we try to acess the content of memory block then we’ll get garbage values.

calloc

函数声明:

1
void	*calloc(size_t __count, size_t __size) __result_use_check __alloc_size(1,2);

参数说明:

  1. Number of blocks to be allocated.
  2. Size of each block.

calloc() allocates the memory and also initializes the allocates memory block to zero. If we try to access the content of these blocks then we’ll get 0.

因为calloc会将申请的内存初始化为0或NULL,所以在需要初始化的场景下该函数会很方便,比如创建一个结构体,创建一个数组。

realloc

函数声明:

1
void	*realloc(void *__ptr, size_t __size) __result_use_check __alloc_size(2);

参数说明:

  • ptr − This is the pointer to a memory block previously allocated with malloc, calloc or realloc to be reallocated. If this is NULL, a new block is allocated and a pointer to it is returned by the function.
  • This is the new size for the memory block, in bytes. If it is 0 and ptr points to an existing block of memory, the memory block pointed by ptr is deallocated and a NULL pointer is returned.

函数说明:

realloc可以用来重新调整之前分配的内存大小。指针p必须为指向堆内存空间的指针,即由malloc函数、calloc函数或realloc函数分配空间的指针或者为NULL。size = 0,行为未定义,一种实现是:释放指针p指向的内存,并返回NULL。

realloc函数有两种行为:

  1. 在原来的内存空间上进行扩张或收缩。min(newSize, oldSize)区域内的内容不变。如果是扩张则扩张部分的内存空间是未初始化的。
  2. 申请一块全新的内存空间,并将原来指向空间的内容依次复制到新的内存空间上,p之前指向的空间被释放。扩张部分的内存空间是未初始化的。

调用realloc后,不应该再使用原来的指针p,如果使用则行为未定义。

上面三个申请内存的函数,在使用完后都需要调用free释放内存。

参考

realloc 比较清晰

realloc 很详细。这个网站也不错,囊括了大部分C++的函数说明。

觉得文章有帮助可以打赏一下哦!