您的位置:首页 > 编程语言 > C语言/C++

C语言 malloc calloc realloc 区别

2015-11-22 16:14 471 查看
<span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size:18px;">man 手册对于calloc malloc realloc和free的定义如下:</span></strong></span>


calloc, malloc, free, realloc - Allocate and free dynamic memory

#include <stdlib.h>

void *calloc(size_t nmemb, size_t size);
void *malloc(size_t size);
void free(void *ptr);
void *realloc(void *ptr, size_t size);

calloc()
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().

calloc 函数分配nmemb块长度为size的内存,并返回分配的内存地址,并且分配的内存已经被初始化。如果nmemb 或者 size 为0,calloc的返回不是空,也不是一个合法的指针,该指针不用调用free函数进行初始化。

malloc()
 allocates size bytes and returns a pointer to the allocated memory.  The memory is not cleared.  If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to
free().


malloc 函数分配一块长度为size的内存,返回指向分配的内存地址,该内存并未被初始化,如果size为0, 返回不是空,也不是一个合法的指针,该指针不用调用free函数进行初始化。

free() frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or  realloc().Otherwise, or if free(ptr) has already been
called before, undefined behavior occurs.  If ptr is NULL, no operation is performed.

free函数释放malloc,calloc或者realloc所分配的内存。如果free函数重复调用,将该调用出出现未定义的行为。如果ptr为空,不执行任何操作。
realloc()  changes the size of the memory block pointed to by ptr to size bytes.  The contents will be unchanged to the minimum of the old and new sizes; newly allocated memory
will be uninitialized.  If ptr is NULL, then the call is equivalent to malloc(size), for all values  of size; if size is equal to zero, and ptr is not NULL, then the call is equivalent to free(ptr).  Unless ptr is NULL, it must have been returned by an earlier
call to malloc(), calloc() or realloc().  If the area pointed to was moved, a free(ptr) is done.

realloc函数改变ptr的内存大至size字节,之前ptr指向的内容并未发生改变,新分配的内存未被初始化。如果ptr为空,该调用类似malloc(size),如果size为0,且ptr不为空,则该调用类似free(ptr).
如果ptr不为空,则ptr一定要为malloc,calloc或者realloc的返回值。如果ptr指向的地址发生变化,free会被调用(意思即当realloc改变的了ptr的指针,free(ptr)会被调用的)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: