malloc c语言

page 101

the standard library provides analogous functions called malloc and free that have no such restrictions;

 

page 167

the functions malloc and calloc obtain blocks of memory dynamically.

void *malloc( size_t n)

returns a pointer to n bytes of uninitialized storage, or NULL if the request can not be satisfied.

void *calloc( size_t n, size_t size)

returns a pointer to enough space for an array of n objects of the specified size, or NULL if the request cannot be satisfied. The storage is intialized to zero.

The pointer returned by malloc or calloc has the proper alignment for the object in question, but it must be cast into the appropriate type, as in

int *ip;
ip = ( int * ) calloc ( n ,sizeof( int ) );

free (p) frees the space pointed to by p, where p was originally obtained by a call to malloc or calloc. There are no restrictions on the order in which space is freed, but it is a ghastly error to free something not obtained by
calling calloc or malloc.

 

意思就是c标准库文件stdlib.h里面带有的malloc函数

它的函数定义张这样:

void *malloc( size_t size)

从这个我们可以看出,这个函数返回值为空指针类型。该指针指向根据我们的需要分配的内存空间,如果请求失败的话(即空间分配失败的话)返回NULL。

下面例子说

str = ( char * ) malloc( 15 );

 即分配15byte空间,然后malloc函数返回一个指向这个15byte空间的void*,空指针类型。再强制类型转换成char *类型

两张图片来自https://www.tutorialspoint.com/c_standard_library/c_function_malloc.htm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值