invalid conversion from `void*' to `char*' when using malloc?

限于喜欢 提交于 2019-12-17 08:54:49

问题


I'm having trouble with the code below with the error on line 5:

error: invalid conversion from void* to char*

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");
}

回答1:


In C++, you need to cast the return of malloc()

char *foo = (char*)malloc(1);



回答2:


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 a char* to a void*.

If you change your file to a .c then it will expect C code. In C, you do not need to specify a cast between void* and another pointer type. If you change your file to a .c it will compile successfully.




回答3:


I assume this is the line with malloc. Just cast the result then - char *foo = (char*)...




回答4:


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 of malloc to the proper type.



来源:https://stackoverflow.com/questions/5099669/invalid-conversion-from-void-to-char-when-using-malloc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!