0

Hi all:

The function malloc returns a void* pointer, and so I need to explicitly use type cast e.g.: (struct*)malloc(sizeof(Message_from_server));
I am wondering if it is a legal expression or at least, I should give it a tag name like (struct*message_from_server)malloc(sizeof(Message_from_server));

Thanks

4
Contributors
5
Replies
6
Views
11 Years
Discussion Span
Last Post by Ancient Dragon
0

If you are compiling a C program as C++ (with .cpp extension instead of .c extention), then you will have to typecase malloc because the compiler is compiling it as a c++ program, and c++ requires the typecase. If, on the otherhand, the file is *.c extension, then no typecase is necessary (permissible but not necessary).

0

The correct typecast is (see place ment of the asterisk)

// C example
(struct message_from_server*)malloc(sizeof(struct Message_from_server)); 

// C++ example (keyword struct not necessary)
(message_from_server*)malloc(sizeof(Message_from_server));
0

Question?

Should you be using malloc in c++, isn't it frowned upon?

Yes -- but it can be much more serious problem that just "frowned upon" because malloc() does not call class constructors or destructors.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.