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)会被调用的)。
相关文章推荐
- 【面试题】C语言:模拟实现strncpy,尝试比较strncpy与strcpy区别。
- C语言二叉树的层序遍历
- C++ 学习(虚基类)
- 在C++中使用golang的协程
- c++虚函数逆向分析
- 在C++中使用golang的协程
- C语言学习web服务器小实例
- hiho 12 树的dp
- C语言素数的多种求法
- c语言内存模型
- c语言学习第一天
- C++IO流简介
- C++IO流简介
- C++指针和引用的区别
- 【C++】中序线索化二叉树及其遍历
- C++ Runtime Error :STL list "list iterator not incrementable"
- 学生成绩管理系统课程设计(C语言,链表实现)
- C++构造与析构函数中调用虚函数的问题
- 2014传智播客C++第三期基础班+就业班至9月份 完整版
- ICL Auto Vectorization