malloc()
头文件
#include<stdlib.h>
函数原型
void *malloc(size_t size);
相关函数
void *calloc(size_t nmemb, size_t size);
void free(void *ptr);
void *realloc(void *ptr, size_t size);
Description
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().
Attention
- malloc()从内存堆里分配内存给应用程序,由低地址开始分配。每次在malloc()需要内存的时候只要低地址有内存可用(比如刚被free()的内存区域),就会先对该地址分配。
- malloc()分配的内存不保证是干净的,可通过memset()函数对对应地址内存初始化。
- malloc(0)的返回值有两种情况。NULL或特殊值,特殊值可传给free()。
Example
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
char *p = (char*)malloc(1);
printf("pointer of p is: %p\n",p);
free(p);
p = (char*)malloc(1);
printf("pointer of p is: %p\n",p);
}
print information:
pointer of p is: 0x8914008
pointer of p is: 0x8914008
free()
头文件
#include<stdlib.h>
函数原型
void free(void *ptr);
Description
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 alreadly benn called before, undefined behavior occurs. If ptr is NULL, no operation is performed.
Attention
- free()只接收malloc(),calloc(),realloc()返回的指针
- 警惕对指针进行二次free()调用
- free(p)成功后,p仍然是指向原来的地址,不是为NULL;
realloc()
头文件
#include<stdlib.h>
函数原型
void *realloc(void *ptr,size_t size);
Description
realloc() changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged to the minimun of the old and new sized. newly alloccated memoty 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, the 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.
Attention
realloc(NULL,size) = malloc(size);
realloc(ptr,0) = free(ptr);