In C, the malloc function is used to allocate memory. Its prototype is:
void *malloc(size_t size); |
It returns a void pointer (void *), which indicates that it is a pointer to a region of unknown data type therefore it is a type-unsafe behaviour: malloc allocates based on byte count but not on type. In C++, the new operator returns a pointer whose type relies on the operand. So, you should cast the returned pointer to a specific type:
int *ptr; ptr = malloc(1024 * sizeof (*ptr)); // Without a cast ptr = (int *) malloc(1024 * sizeof (int)); // With a cast |
Advantages to casting
- compatibility with C++, which does require the cast to be made.
- If the cast is present and the type of the left-hand-side pointer is subsequently changed, a warning will be generated to help the programmer in correcting behaviour that otherwise could become erroneous.
- The cast allows for older versions of malloc that originally returned a char *.
Disadvantages to casting
- Under the ANSI C standard, the cast is redundant.
- Adding the cast may mask failure to include the header stdlib.h, in which the prototype for malloc is found:
in the absence of a prototype for malloc, the standard requires that the C compiler assume malloc returns an int. If there is no cast, a warning is issued when this integer is assigned to the pointer; however, with the cast, this warning is not produced, hiding a bug.
References: wikipedia
See also : allocation 2D arrays in C
Please follow and like us:
2 Responses to Malloc and Casting