malloc函数
- 头文件:
stdlib.h
,若代码中涉及内存的分配、释放,需要写:#include<stdlib.h>
- 函数原型:
void* malloc (size_t size);
- 功能:Allocate memory block (动态分配内存)
Allocates a block of size bytes of memory, returning a pointer to the beginning of the block.
List p = (List)malloc(sizeof(struct LNode)); //分配LNode结点大小的内存,成功后返回指向新内存的指针;
- 与
new
的区别:参考【转】new和malloc的区别
free函数
将动态申请的内存空间释放,避免发生内存泄漏。
- 函数原型:
void free (void* ptr);
- 功能:Deallocate memory block
A block of memory previously allocated by a call to malloc, calloc or realloc is deallocated, making it available again for further allocations.
Notice that this function does not change the value of ptr itself, hence it still points to the same (now invalid) location.
注:博文中“解读free”部分的四个注释需要更深入理解。