tags:

views:

85

answers:

3

Hi,

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...

Thanks in advance.

+7  A: 

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!

Oli Charlesworth
You can `static_cast` from `void*`, and probably should if only because a `reinterpret_cast` will cause people to panic unnecessarily.
Steve Jessop
This is not a situation for reinterpret_cast<> which you should reserve for very specific situations where you actually want people to re-check the code (especially when porting).
Martin York
@Martin, @Steve: You are both right, answer updated...
Oli Charlesworth
A: 

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); 
Sam Dufel
Only in C++. And if you're in C++ you shouldn't be using C style casts or malloc anyway.
Billy ONeal
+1  A: 

In C++ it is not allowed to simply assing 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 assing 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 nessesary 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.

Nils Pipenbrinck
"In general you shouldn't use malloc and free unless you have to". Shouldn't use new[] and delete[] unless you have to either. `vector` does fine almost all the time.
Steve Jessop
And you shouldn't use c style casts in c++ either.
Billy ONeal