Gareth
Gareth

Reputation: 11

C2440 error when using malloc c++

i was trying the code of "KEYVIEW1.C − Charles Petzold, 1998 " in visual studio but i encountered an error by this part of the code:

pmsg =(void*) malloc(cLinesMax * sizeof (MSG));

the error is :

Error 1 error C2440: '=' : cannot convert from 'void *' to 'PMSG' d:\win32 projects\win32project8\win32project8\win32project8.cpp 97 1 Win32Project8

can any one help me solving this problem ?

Upvotes: 1

Views: 868

Answers (3)

Iyashi
Iyashi

Reputation: 582

The error is caused by (void *)malloc(..).
malloc() doesn't know your variable type (MSG *) so it returns a typeless pointer (void *).
Now you want to set a MSG * to a void * and that's where the error happens.
MSG * and void * obviously aren't the same types.

Don't use malloc() in c++: Why?, Why?

Code examples:
If you still want to use malloc(), here is how:

MSG *pmsg = (MSG *)malloc(cLinesMax * sizeof(MSG)); // Allocate Memory
... pmsg[0].member = "blub";    // Do stuff with pmsg
free( pmsg );                   // Delete dynamic allocated memory

If you want to use the c++-way, here is how:

MSG *pmsg = new MSG[cLinesMax]; // Allocate an Array of MSG's with size $cLinesMax
... pmsg[0].member = "blub";    // Do stuff with pmsg
delete[] pmsg;                  // Delete dynamic allocated memory 

The c++-way is more readable in my opinion and new and delete are safer than malloc and free.

Clarification example: http://ideone.com/46twoD

In fact: YOU make less errors with new and delete!

  1. malloc() returns void *
    You have to cast it to MSG * yourself.
    new casts it for you
  2. malloc() takes bytes count as an argument, which means
    You have to calculate bytes count yourself (num * sizeof(MSG)).
    You can miscalculate the bytes count (e.g. sizeof(MSG) vs sizeof(MSG *)) new automatically calculates bytes count for you

Upvotes: 2

Mohsin Khan
Mohsin Khan

Reputation: 33

To remove the error, either use a C compiler; or if you want to stick with a C++ compiler, then you need to explicitly type cast the return value of malloc.

Similar problem is resolved here: Cannot convert from 'void *' to 'node *'

Upvotes: 1

roalz
roalz

Reputation: 2788

Suggestion
DO NOT use malloc() in C++ programs, prefer using new or, even better RAII techniques.

If you are still forced to use malloc() for whatever reason, you have to cast the void* returned by malloc() to the receiving variable pointer type, in your case probably:

pmsg = (MSG*)malloc(cLinesMax * sizeof(MSG));

Upvotes: 1

Related Questions