Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

malloc

g++

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");
}
like image 997
pandoragami Avatar asked Feb 24 '11 02:02

pandoragami


3 Answers

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

char *foo = (char*)malloc(1);
like image 61
karlphillip Avatar answered Nov 16 '22 17:11

karlphillip


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.

like image 41
Marlon Avatar answered Nov 16 '22 16:11

Marlon


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

like image 7
viraptor Avatar answered Nov 16 '22 17:11

viraptor