Baldrick
Baldrick

Reputation: 11012

Why is there (void*) in front of malloc?

void* buffer = (void*)malloc(100);

By prefixing the malloc() function with (void*), what is being achieved, are we overriding the return type?

Upvotes: 0

Views: 174

Answers (3)

Luchian Grigore
Luchian Grigore

Reputation: 258618

In this particular case, it does nothing. However, since C++ is much more strict than C regarding type safety, you generally need to cast the return of malloc:

void* x = malloc(100);       //OK in C/C++
int*  y = malloc(100);       //OK in C, error in C++
int*  z = (int*)malloc(100); //OK in C/C++, not recommended for C

However, since you use C++, I can't not tell you that you should use new instead.

Upvotes: 5

inspector-g
inspector-g

Reputation: 4176

The return type of the call to malloc is being explicitly cast to a void pointer. This is sort of redundant, as it already returns a void*, but is probably possibly present to clarify the developer's intention (or he just screwed up).

Upvotes: 4

Andreas Brinck
Andreas Brinck

Reputation: 52539

Nothing is achieved since malloc already returns a void pointer. This is equivalent to:

void* buffer = malloc(100);

Upvotes: 6

Related Questions