32 - malloc()函数

1 函数原型

malloc():分配内存块,函数原型如下:

void* malloc (size_t size);

cstdlib库描述如下:

Allocate memory block
1. Allocates a block of size bytes of memory, returning a pointer to the beginning of the block.
2. The content of the newly allocated block of memory is not initialized, remaining with indeterminate values.
3. If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced.
  1. malloc()函数:
    (1)用于向系统申请分配size个字节的内存块;
    (2)用于动态内存分配,允许程序在运行时根据需要分配内存;
  2. 注意事项
    (1)类型转换:应将malloc()函数返回的void*型指针转换为所需类型的指针;
    (2)检查返回值:应检查malloc()函数的返回值是否为NULL,以判断内存分配是否成功;
    (3)内存初始化:malloc()函数分配的内存是未初始化的,值是不确定的;
    (4)内存释放:malloc()函数分配的内存使用完后,应使用free()函数释放,以避免内存泄漏;释放后,应将指针设置为NULL,防止野指针问题

2 参数

malloc()函数只有一个参数size:

  1. 参数size是向系统申请分配的内存块的大小,单位为字节,类型为size_t。

cstdlib库描述如下:

size
1. Size of the memory block, in bytes.
2. size_t is an unsigned integral type.

3 返回值

malloc()函数的返回值类型为void*型:

  1. 分配成功,返回指向新分配的内存块的指针;
  2. 分配失败,返回NULL。

cstdlib库描述如下:


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值