Malloc and Casting

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:
This entry was posted in Computer Science and tagged , . Bookmark the permalink.

2 Responses to Malloc and Casting

  1. myrta says:

    I would be interested in testing the spectrum module from your software part. I see that is released under public licence, but I could not find anywhere how to download or get it.


    • admin says:

      I’m putting the code on an open source repository and it should be downloadable (at least part of it) very soon (1 week or 2).
      thanks for your interests

Leave a Reply

Your email address will not be published.