4
votes

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

3
If you're trying to compile C code, use a C compiler. - chris
malloc return void* you need to explicitly cast to MEMBLOCK*. Like this MEMBLOCK *mb = (MEMBLOCK*)malloc(sizeof(MEMBLOCK)); or better MEMBLOCK *mb = static_cast<MEMBLOCK*>(malloc(sizeof(MEMBLOCK))); - NetVipeC
MEMBLOCK *mb = (MEMBLOCK*)malloc(sizeof(MEMBLOCK)); or /TC option - BLUEPIXY

3 Answers

3
votes

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.

3
votes

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;
2
votes

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;
}