C++ malloc()

C++ 中的 malloc() 函数为 指针 分配一块未初始化的内存。它定义在 cstdlib 头文件中。

示例

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {

  // allocate memory of int size to an int pointer
  int* ptr = (int*) malloc(sizeof(int));

  // assign the value 5 to allocated memory
  *ptr = 5;

  cout << *ptr;

  return 0;
}

// Output: 5

malloc() 语法

malloc() 的语法是

malloc(size_t size);

这里,size 是我们想要分配的内存的大小(以字节为单位)。


malloc() 参数

malloc() 函数接受以下参数

  • size - 一个无符号整数值(转换为 size_t),表示内存块的大小(以字节为单位)

malloc() 返回值

malloc() 函数返回

  • 一个指向函数分配的未初始化内存块的 void 指针
  • 如果分配失败,则返回 null 指针

注意: 如果大小为零,则返回值取决于库的实现。它可能是一个 null 指针,也可能不是。


malloc() 原型

在 cstdlib 头文件中定义的 malloc() 的原型是

void* malloc(size_t size);

由于返回类型是 void*,我们可以 显式类型转换 它为大多数其他基本类型,而不会出现问题。


示例 1:C++ malloc()

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {

// allocate 5 int memory blocks int* ptr = (int*) malloc(5 * sizeof(int));
// check if memory has been allocated successfully if (!ptr) { cout << "Memory Allocation Failed"; exit(1); } cout << "Initializing values..." << endl << endl; for (int i = 0; i < 5; i++) { ptr[i] = i * 2 + 1; } cout << "Initialized values" << endl; // print the values in allocated memories for (int i = 0; i < 5; i++) { // ptr[i] and *(ptr+i) can be used interchangeably cout << *(ptr + i) << endl; } // deallocate memory free(ptr); return 0; }

输出

Initializing values...

Initialized values
1
3
5
7
9

在这里,我们使用 malloc()ptr 指针分配了 5 个 int 类型内存块。因此,ptr 现在作为一个数组使用。

int* ptr = (int*) malloc(5 * sizeof(int));

请注意,我们已经将 malloc() 返回的 void 指针 转换为 int*

然后,我们使用 if 语句检查分配是否成功。如果不成功,我们退出程序。

if (!ptr) {
  cout << "Memory Allocation Failed";
  exit(1);
}

然后,我们使用 for 循环为分配的内存块初始化整数值,并使用另一个 for 循环打印这些值。

最后,我们使用 free() 函数释放了内存。

free(ptr);

示例 2:C++ malloc() 尺寸为零

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {

// allocate memory of size 0 int *ptr = (int*) malloc(0);
if (ptr==NULL) { cout << "Null pointer"; } else { cout << "Address = " << ptr; } // deallocate memory free(ptr); return 0; }

输出

Address = 0x371530

在这里,我们使用 malloc()ptr 指针分配了大小为 0int 类型内存。

int* ptr = (int*) malloc(0);

然后,我们使用 if 语句检查 malloc() 返回的是 null 指针还是地址。

最后,我们使用 free() 释放了内存。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战