malloc(),free()与realloc()

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
  1. malloc()从内存堆里分配内存给应用程序,由低地址开始分配。每次在malloc()需要内存的时候只要低地址有内存可用(比如刚被free()的内存区域),就会先对该地址分配。
  2. malloc()分配的内存不保证是干净的,可通过memset()函数对对应地址内存初始化。
  3. 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
  1. free()只接收malloc(),calloc(),realloc()返回的指针
  2. 警惕对指针进行二次free()调用
  3. 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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值