来自“void*”的无效转换到“char*”什么时候使用malloc?
我在使用下面的代码时遇到了问题,第 5 行出现错误:
错误:从
void*
到char*
的转换无效
我正在使用带代码块的 g++,并尝试将此文件编译为 cpp 文件。有关系吗?
#include <openssl/crypto.h>
int main()
{
char *foo = malloc(1);
if (!foo) {
printf("malloc()");
exit(1);
}
OPENSSL_cleanse(foo, 1);
printf("cleaned one byte\n");
OPENSSL_cleanse(foo, 0);
printf("cleaned zero bytes\n");
}
I'm having trouble with the code below with the error on line 5:
error: invalid conversion from
void*
tochar*
I'm using g++ with codeblocks and I tried to compile this file as a cpp file. Does it matter?
#include <openssl/crypto.h>
int main()
{
char *foo = malloc(1);
if (!foo) {
printf("malloc()");
exit(1);
}
OPENSSL_cleanse(foo, 1);
printf("cleaned one byte\n");
OPENSSL_cleanse(foo, 0);
printf("cleaned zero bytes\n");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 C++ 中,您需要转换
malloc()
的返回值In C++, you need to cast the return of
malloc()
C++ 被设计为比 C 更加类型安全,因此您无法(自动)将 从
void*
转换为另一种指针类型。由于您的文件是.cpp
,您的编译器需要 C++ 代码,并且如前所述,您对 malloc 的调用将不会编译,因为您将char*
分配给无效*
。如果您将文件更改为
.c
那么它将需要 C 代码。在 C 中,您不需要指定void*
和其他指针类型之间的转换。如果将文件更改为.c
它将成功编译。C++ is designed to be more type safe than C, therefore you cannot (automatically) convert from
void*
to another pointer type. Since your file is a.cpp
, your compiler is expecting C++ code and, as previously mentioned, your call to malloc will not compile since your are assigning achar*
to avoid*
.If you change your file to a
.c
then it will expect C code. In C, you do not need to specify a cast betweenvoid*
and another pointer type. If you change your file to a.c
it will compile successfully.我认为这是与 malloc 相关的行。只需转换结果即可 -
char *foo = (char*)...
I assume this is the line with malloc. Just cast the result then -
char *foo = (char*)...
那么,你的意图是什么?您想编写 C 程序还是 C++ 程序?
如果你需要一个 C 程序,那么不要将其编译为 C++,即要么不给你的文件提供“.cpp”扩展名,要么明确要求编译器将你的文件视为 C。在 C 语言中,你不应该转换结果
malloc
。我认为这就是您所需要的,因为您将问题标记为 [C]。如果您需要一个使用
malloc
的 C++ 程序,那么您别无选择,只能将malloc
的返回值显式转换为正确的类型。So, what was your intent? Are you trying to write a C program or C++ program?
If you need a C program, then don't compile it as C++, i.e. either don't give your file ".cpp" extension or explicitly ask the compiler to treat your file as C. In C language you should not cast the result of
malloc
. I assume that this is what you need since you tagged your question as [C].If you need a C++ program that uses
malloc
, then you have no choice but to explicitly cast the return value ofmalloc
to the proper type.