curiousity
curiousity

Reputation: 4741

use malloc leads to error

I am trying to translate some code from objective c to unmanaged c++ I have this operation

Buffer* ir =malloc( sizeof( Buffer ) );

error: expression must have pointer-to type? the same error goes into this code

ir->buffer = malloc( bufferSize );

Could you please provide me correct use of malloc in this unmanaged c++?

Upvotes: 2

Views: 170

Answers (3)

ScarletAmaranth
ScarletAmaranth

Reputation: 5101

I would strongly suggest you use new instead of malloc in c++. Malloc is ENTIRELY unaware of constructors and it's more often than not considered a good practise to use ' new ' (and therefore it's twin ' delete ').

Do make sure not to use malloc with delete or new with free though, i've seen what it can do and let me tell you it's not pleasant.

Upvotes: 0

Try

Buffer *ir = (Buffer*) malloc (sizeof(Buffer));

However, the better C++ way is to have a constructor in the Buffer class and then use something like

Buffer *ir = new Buffer;

or perhaps (if the constructor take some arguments)

Buffer *ir = new Buffer(args);

Upvotes: 1

trojanfoe
trojanfoe

Reputation: 122391

malloc() returns a void * which might be leading to this issue. You can cast the return:

Buffer *ir = (Buffer *)malloc(sizeof(Buffer));

or, if you're using C++, you should use new instead:

Buffer *ir = new Buffer;

(If you do, don't forget to change the free() to delete though).

Upvotes: 6

Related Questions