Malloc C 和 C++ 代码兼容性
Malloc C and C++ code compatibility
我在 C:
中编写了一个包含以下函数的程序
void *e_malloc(size_t size)
{
void *m = malloc(size);
if (!m)
{
printf("Out of memory, fatal error.");
abort();
}
return m;
}
我将其用作 error free malloc
,当内存不足时退出程序。问题是,当我用 g++
编译 linux 中的代码时,我得到一个错误,因为它说它需要转换,正如你所看到的,我总是 return void pointer 原因就是 malloc
returns(gcc
当然可以编译)。有没有办法可以修改此函数以使其在两个编译器上都可以工作?我每次都必须施放它吗?还有其他选择可以实现我想要做的事情吗?
此外,当我使用 Cmake(通过 Clion IDE)时,代码编译得很好 "-std=C++11"
。这是为什么?
正如编译器错误明确指出的那样,错误出在您的调用代码中,而不是您的 e_malloc
。
你可能有这样的情况:
graph_t *g;
g = e_malloc(sizeof(graph_t));
错误是e_malloc
返回的void *
和预期的graph_t*
之间的类型转换。常规 malloc
显示相同的行为。您需要明确地进行类型转换:
g = (graph_t*)e_malloc(sizeof(graph_t));
你根本不应该在 C++ 中使用这个结构。在 C++ 中,您需要使用 new
,而不是 malloc
- 并且 new
已经抛出异常(默认情况下)。问题已解决。
您可以使其更易于使用宏:
#define e_new(type) ((type*)malloc(sizeof(type)))
#define e_new_array(type, count) ((type*)malloc((count)*sizeof(type)))
用法示例:
graph_t *g = e_new(graph_t);
graph_t *ten_gs = e_new_array(graph_t, 10);
请注意,这 不是 特定于您的 e_malloc
- malloc
本身在 C++ 中也有同样的问题。
我在 C:
中编写了一个包含以下函数的程序void *e_malloc(size_t size)
{
void *m = malloc(size);
if (!m)
{
printf("Out of memory, fatal error.");
abort();
}
return m;
}
我将其用作 error free malloc
,当内存不足时退出程序。问题是,当我用 g++
编译 linux 中的代码时,我得到一个错误,因为它说它需要转换,正如你所看到的,我总是 return void pointer 原因就是 malloc
returns(gcc
当然可以编译)。有没有办法可以修改此函数以使其在两个编译器上都可以工作?我每次都必须施放它吗?还有其他选择可以实现我想要做的事情吗?
此外,当我使用 Cmake(通过 Clion IDE)时,代码编译得很好 "-std=C++11"
。这是为什么?
正如编译器错误明确指出的那样,错误出在您的调用代码中,而不是您的 e_malloc
。
你可能有这样的情况:
graph_t *g;
g = e_malloc(sizeof(graph_t));
错误是e_malloc
返回的void *
和预期的graph_t*
之间的类型转换。常规 malloc
显示相同的行为。您需要明确地进行类型转换:
g = (graph_t*)e_malloc(sizeof(graph_t));
你根本不应该在 C++ 中使用这个结构。在 C++ 中,您需要使用 new
,而不是 malloc
- 并且 new
已经抛出异常(默认情况下)。问题已解决。
您可以使其更易于使用宏:
#define e_new(type) ((type*)malloc(sizeof(type)))
#define e_new_array(type, count) ((type*)malloc((count)*sizeof(type)))
用法示例:
graph_t *g = e_new(graph_t);
graph_t *ten_gs = e_new_array(graph_t, 10);
请注意,这 不是 特定于您的 e_malloc
- malloc
本身在 C++ 中也有同样的问题。