C++ getting error C2440
Solution 1
In C++ You may not assign a pointer of type void *
to a pointer of some other type. So for example instead of writing
MEMBLOCK *mb = malloc(sizeof(MEMBLOCK));
You have to write
MEMBLOCK *mb = ( MEMBLOCK * )malloc(sizeof(MEMBLOCK));
Also you have to change other statements where there is the same problem. It seems these statements are
mb->addr = ( unsigned char * )meminfo->BaseAddress;
mb->buffer = ( unsigned char * )malloc(meminfo->RegionSize);
It is a good example of that you always should use an explicit casting even in C. That makes the code more safe and clear.
Solution 2
Since you're programming in C++, you should not use the old C function malloc
. Instead I would recommend that you use the C++ new
construct:
MEMBLOCK *mb = new MEMBLOCK;
Solution 3
malloc()
returns void*
, and C++ does not automatically cast void*
to a different pointer type. So you have to cast the return value:
MEMBLOCK *mb = (MEMBLOCK*) malloc(sizeof(MEMBLOCK));
Try:
MEMBLOCK* create_memblock (HANDLE hProc, MEMORY_BASIC_INFORMATION *meminfo)
{
MEMBLOCK *mb = (MEMBLOCK*)malloc(sizeof(MEMBLOCK));
if (mb)
{
mb->hProc = hProc;
mb->addr = meminfo->BaseAddress;
mb->size = meminfo->RegionSize;
mb->buffer = malloc(meminfo->RegionSize);
mb->next = NULL;
}
return mb;
}
user3735032
Updated on June 25, 2020Comments
-
user3735032 almost 4 years
Hello I'm using Visual Studio c++ 2010
I'm having a problem with this code ( it's taken from C language code ) :
MEMBLOCK* create_memblock (HANDLE hProc, MEMORY_BASIC_INFORMATION *meminfo) { MEMBLOCK *mb = malloc(sizeof(MEMBLOCK)); if (mb) { mb->hProc = hProc; mb->addr = meminfo->BaseAddress; mb->size = meminfo->RegionSize; mb->buffer = malloc(meminfo->RegionSize); mb->next = NULL; } return mb; }
I'm having these errors :
error C2440: 'initializing' : cannot convert from 'void *' to 'MEMBLOCK *' error C2440: '=' : cannot convert from 'PVOID' to 'unsigned char *' error C2440: '=' : cannot convert from 'void *' to 'unsigned char *'
I'm kinda newbie. Can you please provide a converted code for this that actually works with c++.
Thank you
-
Some programmer dude almost 10 yearsYou may want to say why the OP have to cast the return. Because, as we all know, in C you should not cast the return of
malloc
. -
Quentin almost 6 yearsCasting
void *
in C is neither safer nor clearer, it's completely redundant. The only advantage is polyglottism.