c语言常用内存分配函数详解

本文详细介绍了C语言中常用的内存分配函数:malloc、free、realloc和calloc的功能与使用方法。malloc用于分配指定大小的连续内存块;free释放由malloc分配的内存;realloc调整已分配内存的大小;calloc为数组分配内存并初始化为零。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

NAME

malloc, free, realloc, calloc - main memory allocator

SYNOPSIS

char *malloc (size) unsigned size;
free (ptr)
char *ptr;

char *realloc (ptr, size)
char *ptr;
unsigned size;

char *calloc(nelem, eisize)
unsigned elem, eisize;

DESCRIPTION

malloc and free provide a simple general-purpose memory allocation package. malloc returns a pointer to a block of at least size bytes beginning on a word boundary.

The argument to free is a pointer to a block previously allocated by malloc; this space is made available for further allocation, but its contents are left undisturbed.

Grave disorder will result if the space assigned by malloc is overrun or if some random number is handed to free.

malloc allocates the first big enough contiguous reach of free space found in a circular search from the last block allocated or freed, coalescing adjacent free blocks as it searches. It calls sbrk (see brk(2P) ) to get more memory from the system when there is no suitable space already free.

realloc changes the size of the block pointed to by ptr to size bytes and returns a pointer to the (possibly moved) block. The contents will be unchanged up to lesser of the new and old sizes.

realloc also works if ptr points to a block freed since the last call of malloc, realloc, or calloc; thus sequences of free, malloc, and realloc can exploit the search strategy of malloc to do storage compaction.

calloc allocates space for an array of nelem elements of size eisize. The space is initialized to zeros.

Each of the allocation routines return a pointer to space suitably aligned (after possible pointer coercion) for storage of any type of object.

DIAGNOSTICS

malloc, realloc and calloc return a null pointer (0) if there is no available memory or if the arena has been detectably corrupted by storing outside the bounds of a block. When realloc returns 0, the block pointed to by ptr may be destroyed.  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值