Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: malloc : error: invalid conversion from ‘void*’ to ‘uint8_t*’

Tags:

c++

I got this problem:

invalid conversion from ‘void*’ to ‘uint8_t*’

When doing this:

int             numBytes;
uint8_t         *buffer;

buffer=malloc(numBytes); //error here, why?

or must I have to put it like this?

buffer=malloc(numBytes); 

Please explain this.

like image 327
olidev Avatar asked Oct 24 '10 22:10

olidev


3 Answers

You cannot implicitly cast from void * in C++ (unlike C in this respect). You could do:

buffer = static_cast<uint8_t *>(malloc(numBytes));

but really, you should just be using new/delete instead of malloc/free!

like image 77
Oliver Charlesworth Avatar answered Nov 14 '22 09:11

Oliver Charlesworth


In C++ it is not allowed to simply assign a pointer of one type to a pointer of another type (as always there are exception to the rule. It is for example valid to assign a any pointer to a void pointer.)

What you should do is to cast your void pointer to a uint8_t pointer:

buffer = (uint8_t *) malloc (numBytes);

Note: This is only necessary in C++, in C it was allowed to mix and match pointers. Most C compilers give a warning, but it is valid code.

Since you're using C++ you could also use new and delete like this:

buffer = new uint8_t[numBytes];

and get rid of your buffer using:

delete[] buffer;

In general you shouldn't use malloc and free unless you have to interface with c libraries.

like image 38
Nils Pipenbrinck Avatar answered Nov 14 '22 09:11

Nils Pipenbrinck


Malloc returns a void pointer; when you use it, you have to cast the return value to a pointer to whatever datatype you're storing in it.

buffer = (uint8_t *) malloc(numBytes); 
like image 2
Sam Dufel Avatar answered Nov 14 '22 08:11

Sam Dufel