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库描述如下:

1. On success, a pointer to the memory block allocated by the function.
2. The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable.
3. If the function failed to allocate the requested block of memory, a null pointer is returned.

4 示例

示例代码如下所示:

int main() {
   //
   int* arr = NULL;
   int n = 0;
   int i = 0;
   //
   printf("请输入数组的大小: ");
   scanf("%d", &n);
   // 使用 malloc 分配 n 个 int 类型的内存
   arr = (int*)malloc(n * sizeof(int));
   // 检查 malloc 是否成功
   if (arr == NULL) {
      printf("内存分配失败!\n");
      return 1; // 返回非零值表示错误
   }
   // 打印数组初始值
   printf("数组初始值是:\n");
   for (i = 0; i < n; i++) {
      printf("%x\n", arr[i]);
   }
   // 输入数组元素
   printf("请输入 %d 个整数:\n", n);
   for (i = 0; i < n; i++) {
      scanf("%d", &arr[i]);
   }
   // 输出数组元素
   printf("您输入的数组是:\n");
   for (i = 0; i < n; i++) {
      printf("%d ", arr[i]);
   }
   printf("\n");
   // 释放分配的内存
   free(arr);
   // 将arr设置为NULL
   arr = NULL;
   //
   return 0;
}

代码运行结果如下图所示:

在这里插入图片描述

代码及运行结果分析如下:

  1. 在Win10系统+VS2019环境下,使用malloc()函数分配的内存是未初始化的,值是随机值cd。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值