How to use malloc()
in C++ program?
malloc
,而应改用new
。实际上,在大多数基本的C++编程中,你可能也不应该使用new
。但是,一个基本的例子是声明一个数组:int * array = new int [n]
。这将为n个整数分配空间,并返回指向第一个整数地址的指针。请注意,你必须显式调用delete[]
来释放此内存分配。大多数情况下,你不应该使用它。C++提供了new
和delete
运算符来进行内存管理,甚至可以通过使用智能指针(如Boost库中的boost::shared_ptr
)来避免大部分delete
操作。
示例:
// malloc
Duck* duck = (Duck*)malloc(sizeof(Duck));
// new
Duck* duck = new Duck();
还要注意,如果Duck类有一个非平凡的构造函数,则new
几乎是必需的。(几乎,因为你可以使用带有放置new
的malloc
,但那会使我们偏离主要话题。)
问题 1: "如何从C++中调用malloc函数?"
以下两种方法之一:
#include <cstdlib>
...
int *iptr = (int*) std::malloc(sizeof(*iptr));
#include <stdlib.h>
...
int *iptr = (int*) malloc(sizeof(*iptr));
sizeof(int)
,而不是sizeof(*iptr)
。cstdlib
,则需要命名空间(理论上)。正如Neil所说的,几乎所有实现<cstdlib>
的编译器将malloc
放在全局命名空间中,但标准并不保证这一点。void*
到其他指针类型的自动转换。您可以使用static_cast
而不是C风格的转换,但在这种情况下,个人认为没有必要。malloc
的好理由。与需要分配内存的C代码进行接口操作(因为C代码将释放它)是一个好理由,但即使两个代码片段位于不同的dll中,也可能会遇到问题。int *iptr = new int;
int *intarrayptr = new int[23];
delete iptr;
delete[] intarrayptr;
如果需要将原始数据用于某些无法表示为C++对象/数组的不良目的,请执行以下操作:
unsigned char *twentythreebytes = (unsigned char*) ::operator new(23);
::operator delete(twentythreebytes);
然而,在(设计良好,高级)C ++代码中,像这样从堆中分配内存也相当罕见。尽可能使用自动或成员变量以及标准容器:
#include <vector>
...
std::vector<int> intarray(23);
// no need to delete: the array will be destroyed when it goes out of scope.
std
是C++头文件定义东西的地方。标准C函数确实不是说明这一点的最好例子。 - Steve Jessopnew
和 delete
操作符是 C++ 中替代 malloc()
和 free()
的首选方法,因为它们能够调用类的构造函数和析构函数,并且能够进行内存的分配和释放:
Foo* foo_ptr = new Foo();
delete foo_ptr; // this calls Foo::~Foo(), the destructor
malloc
和free
的唯一时候是为了实现内存管理例程的虚拟版本。#include <cstdlib>
#include <stdexcept>
void* operator new(size_t number_of_bytes) throw (std::bad_alloc)
{
void* p = malloc(number_of_bytes);
if (p == 0) throw std::bad_alloc();
std::cout << "allocated non-array memory @ " << p << '\n';
return p;
}
void* operator new[](size_t number_of_bytes) throw (std::bad_alloc)
{
void* p = malloc(number_of_bytes);
if (p == 0) throw std::bad_alloc();
std::cout << "allocated array memory @ " << p << '\n';
return p;
}
void operator delete(void* p) throw ()
{
if (p == 0) return;
std::cout << "releasing non-array memory @ " << p << '\n';
free(p);
}
void operator delete[](void* p) throw ()
{
if (p == 0) return;
std::cout << "releasing array memory @ " << p << '\n';
free(p);
}
在C++中应避免使用malloc和free,因为它们处理未初始化的内存,而应该使用new和delete。
另一个主要原因是使用new & delete:它们更具可移植性,而malloc/calloc..则不具备(此外,new调用构造函数,delete调用析构函数,而malloc和free则不会)。 通常情况下,您在不同平台上使用new & delete也不会出现问题,因为它们安全地封装了对本机malloc函数的所有调用。
new运算符可用于创建任何类型的对象。它采用以下一般形式-
pointer-variable = new data-type;
malloc
只是一个函数,你需要通过调用它来使用它,就像使用其他函数一样。更重要的是要知道它做什么以及为什么要使用它。你想解决什么问题,认为malloc
可以成为答案? - CB Bailey