My goal is to copy a binary file into a void * pointer data. It doesn’t copy the data, and would like to know what’s wrong.
std::ifstream stream(path.c_str(), std::ios::binary);
std::vector<uint8_t> buffer(std::istreambuf_iterator<char>(stream), {});
void *data = (void*)malloc(size);
memcpy((uint8_t*)data, (uint8_t*)buffer.data(), size);
>Solution :
a void * pointer data
There is no such thing. You can only have data in some object. The kind of object you probably want is an array of char
or unsigned char
. There aren’t any arrays of void
or such that can store values.
A void*
pointer is just a pointer to an object without type information attached or a pointer to memory in which no objects have been created.
The result of malloc
can be either of these types to some degree, but if you intent to copy byte data into the memory you got from it, then you must intent it to be a pointer to an (implicitly-created) array of char
or unsigned char
.
However, buffer
already holds a buffer that is effectively an array of unsigned char
. With buffer.data()
you get a pointer to this buffer. There is no reason to copy the contents of this array into a new array, except if you need to use buffer
for something else, or if you need to transfer ownership of the contents, i.e. if you need the contents to outlive buffer
or if there is someone else responsible for freeing the memory that the void*
member points to.
And any non-const
/volatile
object pointer type is implicitly convertible to void*
. So you only need
void *data = buffer.data();
assuming that the ownership should lie with buffer
and the pointer doesn’t need to outlive buffer
.
Also you need to still make sure that whoever is using the void*
member actually expects it to point to a unsigned char
(or char
) array of size data.size()
.