2

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++?

Michał Powaga
  • 22,561
  • 8
  • 51
  • 62
curiousity
  • 4,703
  • 8
  • 39
  • 59

3 Answers3

6

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).

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • Thank you! Is it correct in the second case write something like ir->buffer = new bufferSize ? – curiousity Nov 21 '11 at 09:05
  • No. You don't specify the type of `ir->buffer` but I suspect it's `unsigned char`, so you would need `ir->buffer = new unsigned char [bufferSize]` to allocate it (and `delete [] ir->buffer` to free it). However this should be done in the `Buffer` class itself, not "outside" really. Sounds like you need to implement a `Buffer` class to do this right. – trojanfoe Nov 21 '11 at 09:10
  • Blind replacement of `malloc()` with `new` is not a good idea - `malloc()` returns null on failure and code checking for that null will no longer work when you replace it with `new`. – sharptooth Nov 21 '11 at 09:12
  • @sharptooth Agreed; the default behaviour for `new` is to throw an exception upon failure, so any `NULL` tests will have to be replaced with `try-catch` blocks. – trojanfoe Nov 21 '11 at 09:16
1

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);
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
0

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.

ScarletAmaranth
  • 5,065
  • 2
  • 23
  • 34