将使用 "new" 分配的内存传递给 C 库是否安全?
Is it safe to pass memory allocated using "new" to C libraries?
我知道 new
delete
与 malloc
free
不相容。
这是否意味着我应该避免将 new
用于将由 C 库使用的内存?
当我将内存传递给 C 库时,使用 new
而不是 malloc
会出现什么问题?
void func()
{
int *p = new int(42);
// Should I insist on using malloc for p if this function is a part
// of a C library?
lib_func(p);
}
内存就是内存,怎么分配都无所谓
只要您将 new
与 delete
、new[]
与 delete[]
以及 malloc
/calloc
与 free
(也realloc
),你还好吧
如果你仔细想想,即使 C 也会在不同的地方分配内存,而且它工作得很好——如果一个库需要一个 int
,你可以在栈上或堆上分配它(或在某些全局存储中):
int a;
int* b = malloc(sizeof(int));
static int c;
some_func(&a);
some_func(b);
some_func(&c);
Does that mean that I should avoid using new for memory that will be used by a C library?
完全没有。内存是一样的,所以如果你提供一个安全的方法来释放内存,你绝对可以把内存传递给 C 库。
int *p = new int(42);
lib_func(p);
delete p;
这是另一个例子:
extern "C" {
int* make_buffer(size_t sz) {
return new int[sz];
}
void use_buffer(int* buf) {
... // do something
}
void free_buffer(int* buf) {
delete[] buf;
}
}
上面的代码让您的 C 代码从您的 C++ 库中请求动态分配的内存。
它和其他任何内存一样都是内存,所以只要 C 库没有 free
它就是安全的。
请注意,在您的示例中,您还可以使用没有分配或释放函数的堆栈内存:
void func()
{
int p;
lib_func(&p);
}
我知道 new
delete
与 malloc
free
不相容。
这是否意味着我应该避免将 new
用于将由 C 库使用的内存?
当我将内存传递给 C 库时,使用 new
而不是 malloc
会出现什么问题?
void func()
{
int *p = new int(42);
// Should I insist on using malloc for p if this function is a part
// of a C library?
lib_func(p);
}
内存就是内存,怎么分配都无所谓
只要您将 new
与 delete
、new[]
与 delete[]
以及 malloc
/calloc
与 free
(也realloc
),你还好吧
如果你仔细想想,即使 C 也会在不同的地方分配内存,而且它工作得很好——如果一个库需要一个 int
,你可以在栈上或堆上分配它(或在某些全局存储中):
int a;
int* b = malloc(sizeof(int));
static int c;
some_func(&a);
some_func(b);
some_func(&c);
Does that mean that I should avoid using new for memory that will be used by a C library?
完全没有。内存是一样的,所以如果你提供一个安全的方法来释放内存,你绝对可以把内存传递给 C 库。
int *p = new int(42);
lib_func(p);
delete p;
这是另一个例子:
extern "C" {
int* make_buffer(size_t sz) {
return new int[sz];
}
void use_buffer(int* buf) {
... // do something
}
void free_buffer(int* buf) {
delete[] buf;
}
}
上面的代码让您的 C 代码从您的 C++ 库中请求动态分配的内存。
它和其他任何内存一样都是内存,所以只要 C 库没有 free
它就是安全的。
请注意,在您的示例中,您还可以使用没有分配或释放函数的堆栈内存:
void func()
{
int p;
lib_func(&p);
}