C Dynamic Memory Allocation - Type Safety

Type Safety

malloc returns a void pointer (void *), which indicates that it is a pointer to a region of unknown data type. The use of casting is only required in C++ due to the strong type system, whereas this is not the case in C. The lack of a specific pointer type returned from malloc is type-unsafe behaviour according to some programmers: malloc allocates based on byte count but not on type. This is different from the C++ new operator that returns a pointer whose type relies on the operand. (see C Type Safety).


One may "cast" (see type conversion) this pointer to a specific type:

int *ptr; ptr = malloc(10 * sizeof (*ptr)); /* without a cast */ ptr = (int *)malloc(10 * sizeof (*ptr)); /* with a cast */

There are advantages and disadvantages to performing such a cast.

Read more about this topic:  C Dynamic Memory Allocation

Famous quotes containing the words type and/or safety:

    “How is freedom measured, in individuals as in nations? By the resistance which has to be overcome, by the effort it costs to stay aloft. One would have to seek the highest type of free man where the greatest resistance is constantly being overcome: five steps from tyranny, near the threshold of the danger of servitude.”
    —Friedrich Nietzsche (1844–1900)

    “There was only one catch and that was Catch-22, which specified that a concern for one’s own safety in the face of dangers that were real and immediate was the process of a rational mind.... Orr would be crazy to fly more missions and sane if he didn’t, but if he was sane he had to fly them. If he flew them he was crazy and didn’t have to; but if he didn’t want to he was sane and had to.”
    —Joseph Heller (b. 1923)